﻿Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.GC
Public Class Frm_INTInStorage

    Implements IDServer.IDServer.IDServer

    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp
    Dim strsql As String
    Dim strsqlelement As String
    Private MasterDS As DataSet
    Private DetailDS As DataSet
    Private StoreDS As DataSet
    Private GoodsDS As DataSet
    Private StoreageDS As DataSet
    Private IsPlace As Boolean
    Private IsAdd As Boolean = False
    Private LastElement As String
    Private bFind As Boolean
    Private bBind As Boolean
    Private IsClose As Boolean
    Public dsc As Boolean
    Public Fields As String
    Private GetPoNum As String
    Private PeriodData As String
    Private SelectNode As TreeNode
    Private WithEvents MainForm As Frm_MainForm
    Private WithEvents ComBo As New ComboBox
    Private WithEvents ComBoUnit As New ComboBox


#Region "Property"

    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property

    Private Sub Frm_INTInStorage_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            LoadGoods()
            IsAmountClose()
            LoadStoreType()
            LoadStorePlace()
            BindGridMaster()
            BindDataGridView()
            BindElementGridView()
            SetGridCaptionVisible(Me.DGV_Master, Fields, "Frm_INTInStorage")
            SetCtlEnable(False)
            LoadPopfrmInfo()
            ClearText()
            Me.LabOperatePerson.Text = PubUserName
            Me.LabOperateDate.Text = ServerDate
            LoadCombox()
            Me.txtPoNo.Enabled = False
            Me.txtelementtimes.Enabled = False
            '' Me.grpbox1.Enabled = False
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Sub

    'Private Sub LoadCombox()

    '    With Me.cmbelementstatus
    '        .Items.Add("一級品")
    '        .Items.Add("二級品")
    '        .Items.Add("三級品")
    '        .Items.Add("四級品")
    '        .SelectedIndex = 0
    '    End With 
    '    With cmbelementunit
    '        .Items.Add("PC")
    '        .SelectedIndex = 0
    '    End With

    'End Sub


    Private Sub LoadCombox()

        Dim sql As String = ""
        Dim dtTable As DataTable

        sql = "select b.* from dbo.BSC_OtherDefineA a inner join BSC_OtherDefineB b on a.Id=b.ItemNo where a.ItemCode='UnitDefin'"

        Try
            dtTable = Exec(sql, E_ExecType.DataTable)

            If dtTable.Rows.Count > 0 Then
                Me.cmbelementunit.DisplayMember = "ListA"
                Me.cmbelementunit.ValueMember = "ListCode"
                Me.cmbelementunit.DataSource = dtTable
                Me.cmbelementunit.DropDownStyle = ComboBoxStyle.DropDownList
                Me.cmbelementunit.SelectedIndex = 0
            End If
            With Me.cmbelementstatus
                .Items.Add("一級品")
                .Items.Add("二級品")
                .Items.Add("三級品")
                .Items.Add("四級品")
                .DropDownStyle = ComboBoxStyle.DropDownList
                .SelectedIndex = 0
            End With
        Catch ex As Exception
            MsgBox("LoadUnitDefine:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly)
        Finally
            dtTable = Nothing
        End Try

    End Sub

    Private Function number(ByVal k As String, ByVal kkk As String) As Integer
        Try
            Dim dsreadnumber As New DataSet
            Dim strsql As String = ""
            strsql = "select * from " & kkk & " where billtype='" & k & "'"
            dsreadnumber = ReturnDataset(strsql)
            If dsreadnumber.Tables(0).Rows.Count > 0 Then
                For Each drow As DataRow In dsreadnumber.Tables(0).Rows
                    number = drow("number")
                Next
            Else
                number = 1
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Private Function updatenumber(ByVal k As String, ByVal kkk As String)
        Try
            Dim strsql As String = ""
            Dim tt = CInt(number("movenum", "number"))
            updatenumber = "update " & kkk & " set number='" & tt & "'+1  where billtype='" & k & "'"

        Catch ex As Exception
            MessageBox.Show(ex.ToString, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Private Function updatenumberelement(ByVal k As String, ByVal kkk As String)
        Try
            Dim strsql As String = ""
            Dim tt = CInt(number("movenum", "number"))
            'updatenumberelement = "update " & kkk & " set number='" & tt & "' + '" + CInt(txtqty.Text) + " '  where billtype='" & k & "'"
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Private Sub btnAddElement_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddElement.Click
        Try
            CreateElement()
        Catch ex As Exception
            MsgBox("btnAddElement_Click:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub CreateElement()
        Try

            If Me.txtBoNum.Text.Length <= 0 Then
                MsgBox("入庫單號不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Exit Sub
            End If

            If Me.txtbarcode.Text.Length <= 0 Then
                MsgBox("貨品條碼不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Exit Sub
            End If

            If Me.txtelementqty.Text.Length <= 0 Then
                MsgBox("請輸入元件包含貨物數量", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Exit Sub
            End If

            If Me.txtelementtimes.Text.Length <= 0 Then
                MsgBox("選擇循環次數，即生成元件數量！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Exit Sub
            End If

            Dim ElementTable As DataTable
            ElementTable = CType(Me.dgv_Element.DataSource, DataTable)
            Dim NewRow As DataRow
            Dim SumGrid As Double = 0

            If ElementTable.Rows.Count > 0 Then
                If ElementTable.Compute("sum(Elementamount)", "") Is DBNull.Value Then
                    SumGrid = 0
                Else
                    SumGrid = ElementTable.Compute("sum(Elementamount)", "")
                End If
            End If



            If ElementTable.Rows.Count > 0 Then
                If Me.rb1.Checked = True Then
                    If Convert.ToDouble(Me.txtGoodsCount.Text) <= (Convert.ToDouble(Me.txtelementqty.Text) * Convert.ToDouble(Me.txtelementtimes.Text) + SumGrid) Then
                        '' Me.LabInfo1.Visible = True
                        '' Me.LabInfo1.Text = "元件數量不能大於總數量！"
                        MessageBox.Show("元件數量不能大於總數量！", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Exit Sub
                    End If
                End If
                If Me.rb2.Checked = True Or Me.rb3.Checked = True Then
                    If Convert.ToDouble(Me.txtGoodsCount.Text) <= (SumGrid) Then
                        ''Me.LabInfo1.Visible = True
                        Me.LabInfo1.Text = "元件數量不能大於總數量！"
                        Exit Sub
                    End If
                End If
            Else
                If Me.rb1.Checked = True Then
                    If Convert.ToDouble(Me.txtGoodsCount.Text) < (Convert.ToDouble(Me.txtelementqty.Text) * Convert.ToDouble(Me.txtelementtimes.Text)) Then
                        Me.LabInfo1.Visible = True
                        Me.LabInfo1.Text = "元件數量不能大於總數量！"
                        Exit Sub
                    End If
                End If
                If Me.rb2.Checked = True Or Me.rb3.Checked = True Then
                    If Convert.ToDouble(Me.txtGoodsCount.Text) <= 0 Then
                        Me.LabInfo1.Visible = True
                        Me.LabInfo1.Text = "元件數量不能大於總數量！"
                        Exit Sub
                    End If
                End If
            End If

            If Convert.ToDouble(Me.txtGoodsCount.Text) < (Convert.ToDouble(Me.txtelementqty.Text) * Convert.ToDouble(Me.txtelementtimes.Text)) Then
                MsgBox("元件數量不能大於總數量！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Exit Sub
            End If
            If Me.dgv_Element.Rows.Count > 0 Then
                Dim SumElement As Double
                For i As Integer = 0 To Me.dgv_Element.Rows.Count - 1
                    SumElement += Convert.ToDouble(Me.dgv_Element.Rows(i).Cells(1).Value)
                Next
                If Convert.ToDouble(Me.txtGoodsCount.Text) <= Convert.ToDouble(SumElement) Then
                    MsgBox("數量超出範圍，不能添加！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Exit Sub
                End If
            End If
            Dim tt = CInt(number("element", "number"))
            Dim kk = txtbarcode.Text
            Dim mm = txtelementtimes.Text
            Dim StorePlace As String
            Dim Batch As String
            Dim ElementNo As Integer
            Dim CycleTimes As String
            Dim sql As String = String.Empty
            Dim dtTable As DataSet


            CycleTimes = txtGoodsCount.Text

            If Me.StorePlace.Text.Length <= 0 Then
                StorePlace = Me.txtplace.Text
            Else
                StorePlace = Me.StorePlace.Text
            End If

            If Me.txtelementbatch.Text.Length <= 0 Then
                Batch = Me.txtbatch.Text
            Else
                Batch = Me.txtelementbatch.Text
            End If

            If Convert.ToInt64(LastElement) = 0 Then

                If Me.rb3.Checked = False Then
                    sql = "select * from Number where BillType='ElementNum';"
                    sql += "select * from Stor_element where Element in (select right('0000000000000'+Convert(varchar(20),Number),13) from Number where BillType='ElementNum')"
                    Try
                        dtTable = Exec(sql, E_ExecType.DataSet)

                        If dtTable.Tables(1).Rows.Count > 0 Then
                            Me.LabInfo1.Text = "生成元件號錯誤，該元件已經存在資料庫中！"
                            Exit Sub
                        End If

                        If dtTable.Tables(0).Rows.Count > 0 Then
                            ElementNo = Val(dtTable.Tables(0).Rows(0).Item("Number")) + 1
                        Else
                            ElementNo = 1
                        End If
                    Catch ex As Exception
                        ex.ToString()
                    End Try
                End If
            Else
                ElementNo = LastElement + 1
            End If
            If Me.rb1.Checked = True Then
                If Me.rb1.Checked = True Then

                    If Me.dgv_Element.Rows.Count > 0 Then
                        If Convert.ToInt64(LastElement) > 0 Then
                            For i As Integer = 0 To CycleTimes - 1
                                NewRow = ElementTable.NewRow
                                NewRow("Element") = Format(CType(LastElement, Integer) + (i + 1), "0000000000000") & "X"
                                NewRow("Elementamount") = Convert.ToInt32(txtelementqty.Text)
                                NewRow("ElementUnit") = cmbelementunit.SelectedValue
                                NewRow("ElementBatch") = Me.txtbatch.Text
                                NewRow("StorePlace") = Me.txtplace.Text
                                NewRow("ElementStatus") = Me.cmbelementstatus.Text
                                ElementTable.Rows.Add(NewRow)
                            Next
                        Else
                            For i As Integer = 0 To CycleTimes - 1
                                NewRow = ElementTable.NewRow
                                NewRow("Element") = Format(ElementNo + i, "0000000000000") & "X"
                                NewRow("Elementamount") = Convert.ToInt32(txtelementqty.Text)
                                NewRow("ElementUnit") = cmbelementunit.SelectedValue
                                NewRow("ElementBatch") = Me.txtbatch.Text
                                NewRow("StorePlace") = Me.txtplace.Text
                                NewRow("ElementStatus") = Me.cmbelementstatus.Text
                                ElementTable.Rows.Add(NewRow)
                            Next
                        End If
                    Else
                        For i As Integer = 0 To CycleTimes - 1
                            NewRow = ElementTable.NewRow
                            NewRow("Element") = Format(ElementNo + i, "0000000000000") & "X"
                            NewRow("Elementamount") = Convert.ToInt32(txtelementqty.Text)
                            NewRow("ElementUnit") = Me.cmbelementunit.SelectedValue
                            NewRow("ElementBatch") = Me.txtbatch.Text
                            NewRow("StorePlace") = Me.txtplace.Text
                            NewRow("ElementStatus") = Me.cmbelementstatus.Text
                            ElementTable.Rows.Add(NewRow)
                        Next
                    End If
                    ElementTable.AcceptChanges()
                    Me.dgv_Element.DataSource = ElementTable
                    LastElement = CType(Replace(Me.dgv_Element.Rows(Me.dgv_Element.Rows.Count - 1).Cells("Element").Value, "X", ""), Integer)
                    IsAdd = True
                    Me.txtelementnum.Text = ""
                    Me.txtelementnum.Focus()
                End If

            ElseIf Me.rb2.Checked = True Then
                Dim item As ListViewItem
                If Me.dgv_Element.Rows.Count <= 0 Then
                    item = New ListViewItem
                    item.Text = Format(tt + 1, "0000000000000") & "X"
                    item.SubItems.Add(txtelementqty.Text)
                    item.SubItems.Add(cmbelementunit.Text.ToString)
                    item.SubItems.Add(Batch)
                    item.SubItems.Add(StorePlace)
                    item.SubItems.Add(cmbelementstatus.Text.ToString.Split(Space(2))(0).ToString)
                    'Me.lsvElement.Items.Add(item)
                Else
                    item = New ListViewItem
                    'item.Text = Format(CInt(lsvElement.Items(lsvElement.Items.Count - 1).Text) + 1, "0000000000000")
                    item.SubItems.Add(txtelementqty.Text)
                    item.SubItems.Add(cmbelementunit.Text.ToString)
                    item.SubItems.Add(Batch)
                    item.SubItems.Add(StorePlace)
                    item.SubItems.Add(cmbelementstatus.Text.ToString.Split(Space(2))(0).ToString)
                    'Me.lsvElement.Items.Add(item)
                End If
            ElseIf Me.rb3.Checked = True Then
                If Me.rb3.Checked = True Then

                    If Me.txtelementnum.Text.Length <= 0 Then
                        Me.LabInfo.Visible = True
                        Me.LabInfo.Text = "元件號不能為空！"
                        Exit Sub
                    End If

                    If Me.dgv_Element.Rows.Count > 0 Then
                        Dim nTable As DataTable = CType(Me.dgv_Element.DataSource, DataTable)
                        Dim Rows() As DataRow = nTable.Select("Element='" & Me.txtelementnum.Text & "'")
                        If Rows.Length > 0 Then
                            Me.LabInfo.Visible = True
                            Me.LabInfo.Text = "該元件已經存在！"
                            Me.txtelementnum.Text = ""
                            Exit Sub
                        End If
                    End If
                    NewRow = ElementTable.NewRow

                    NewRow("Element") = Me.txtelementnum.Text
                    NewRow("Elementamount") = txtelementqty.Text
                    NewRow("ElementUnit") = cmbelementunit.SelectedValue
                    NewRow("ElementBatch") = Me.txtbatch.Text
                    NewRow("ElementPlace") = Me.txtplace.Text
                    NewRow("ElementStatus") = Me.cmbelementstatus.Text
                    ElementTable.Rows.Add(NewRow)
                    ElementTable.AcceptChanges()

                    ''OuterElement = True
                    IsAdd = True
                    Me.txtelementnum.Text = ""
                    Me.txtelementnum.Focus()
                End If
                'For i As Integer = 0 To Me.lsvElement.Items.Count - 1

                '    If Me.lsvElement.Items(i).Tag = item.Tag Then
                '        MsgBox("已經存在相同的元件號!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                '        Exit Sub
                '    End If

                'Next

                'Me.lsvElement.Items.Add(item)

            End If
        Catch ex As Exception
            MsgBox("CreateElement:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub rbtnelement_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rb1.CheckedChanged
        Try
            If rb1.Checked = True Then
                txtelementnum.Enabled = False
                dsc = True
                txtelementtimes.Enabled = True
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub

    Private Sub rbtnelementmanmade_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rb3.CheckedChanged
        Try
            If rb3.Checked = True Then
                txtelementnum.Enabled = True
                txtelementtimes.Text = 1
                txtelementtimes.Enabled = False
                dsc = False
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "error", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub

    Private Sub rbtnonebyoneother_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rb2.CheckedChanged
        Try
            If rb2.Checked = True Then
                txtelementnum.Enabled = False
                txtelementtimes.Enabled = False
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString, Msg.CompanyName)
        End Try
    End Sub

    Private Sub ClearText()
        Try
            Me.txtDeliverNo.Text = ""
            Me.txtDeliverPerson.Text = ""
            Me.txtCarNo.Text = ""
            Me.txtRemark.Text = ""
            Me.LabInfo.Text = ""
            Me.txtDeliverNo.Text = ""
            Me.LabInfo1.Text = ""
            If Me.cbInStoreType.SelectedIndex <> 0 Then
                Me.cbInStoreType.SelectedIndex = 0
            End If
            Me.cbToStore.SelectedIndex = Me.cbToStore.FindString(PubCompanyName)
            Dim Rows() As DataRow = Me.StoreDS.Tables(3).Select("fCode='" & PubCompanyCode & "'")
            If Rows.Length > 0 Then
                Me.cbToStore.Text = Rows(0).Item("fShortName") & ""
            Else
                Me.cbToStore.Text = PubCompanyName
            End If

            'Me.cbToStore.SelectedValue = PubCompanyCode

            Me.cbFromStore.SelectedIndex = 0
            Me.cmbStatus.SelectedIndex = 0
            Me.DGV_Sum.Rows(0).Cells("goodsamount").Value = "0.00"
            Me.DateTimePicker1.Value = ServerDate
            If DetailDS.Tables(0).Rows.Count > 0 Then
                DetailDS.Tables(0).Rows.Clear()
                Me.DGV_Detail.DataSource = DetailDS.Tables(0)
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SetCtlEnable(ByVal b As Boolean)
        Try
            Me.cbInStoreType.Enabled = b
            Me.cbToStore.Enabled = False
            Me.txtDeliverNo.Enabled = b
            Me.DateTimePicker1.Enabled = b
            Me.txtCarNo.Enabled = b
            Me.txtGoodsBarCode.Enabled = b
            Me.DateTimePicker1.Enabled = b
            Me.txtDeliverPerson.Enabled = b
            Me.txtRemark.Enabled = b
            Me.txtdiaobo.Enabled = b And Me.cbInStoreType.SelectedIndex = 3 And (ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit)
            Me.txtBackNo.Enabled = b And Me.cbInStoreType.SelectedIndex = 2 And (ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit)
            Me.txtSaleOrdeNo.Enabled = b And Me.cbInStoreType.SelectedIndex = 4 And (ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit)
            Me.txtPoNo.Enabled = b And Me.cbInStoreType.SelectedIndex = 1 And (ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit)
            Me.DGV_Detail.AllowUserToAddRows = b
            Me.DGV_Detail.AllowUserToDeleteRows = b
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Me.DGV_Detail.Columns("StorePlace").ReadOnly = IsPlace
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub LoadPopfrmInfo()
        Dim sql As String = ""
        Dim m_Ds As New DataSet
        Dim mCount As Integer
        Try

            sql = "select Count(*) from Stor_TradeMaster where TradeType='+' and BoStatus in ('A','C')"

            m_Ds = ReturnDataset(sql)
            If m_Ds.Tables(0).Rows.Count > 0 Then

                mCount = Convert.ToInt64(m_Ds.Tables(0).Rows(0).Item(0))
                If mCount > 0 Then
                    With Popupfrm
                        .CloseButtonClickEnabled = True
                        .TitleClickEnabled = False
                        .TextClickEnabled = True
                        .DrawTextFocusRect = True
                        .KeepVisibleOnMouseOver = True
                        .ReShowOnMouseOver = False
                        AddHandler .TextClick, AddressOf PopupfrmQueryInfo
                        .Show("每日提醒", "你還有 [" & mCount & "] 單尚未審核,請趕快審核吧!", 500, 5000, 500)
                    End With
                End If
            End If
        Catch ex As Exception
            MsgBox("LoadPopfrmInfo:" & ex.Message, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            m_Ds = Nothing
        End Try
    End Sub

    Public Sub PopupfrmQueryInfo(ByVal sender As Object, ByVal e As EventArgs)

        Try
            Dim sql As String = ""

            sql = "select Distinct(a.BoNum),b.TradeType,c.InOrOutType,d.ToStore,e.FromStore,a.StorePlace,a.DeliverNo,a.DeliverPerson,a.DeliverDate,a.DeliverCar,a.Batch,BoStatus=f.ListA,"
            sql += " a.Remark,a.OperatePerson,a.OperateDate,a.CheckPerson,a.CheckDate  from Stor_TradeMaster a left join "
            sql += " (select a.BoNum,b.name as TradeType from Stor_TradeMaster a inner join Stor_tradecode b on a.TradeType=b.AddorNot where b.code='01') b on a.BoNum=b.BoNum left join "
            sql += " (select a.BoNum,b.ListA as InOrOutType from Stor_TradeMaster a inner join BSC_OtherDefineB b on a.InOrOutType=b.ListCode where b.ItemNo=57) c on a.BoNum=c.BoNum left join "
            sql += " (select a.BoNum,b.fShortName as ToStore from Stor_TradeMaster a inner join BSC_StoreHouse b on a.ToStore=b.fCode) d on a.BoNum=d.boNum left join "
            sql += " (select a.BoNum,b.fShortName as FromStore from Stor_TradeMaster a inner join BSC_StoreHouse b on a.FromStore=b.fCode) e on a.BoNum=e.BoNum left join BSC_OtherDefineB f on a.BoStatus=f.ListCode"
            sql += " where f.ItemNo=16 and a.TradeType='+' and BoStatus in ('A','C')"

            MasterDS = ReturnDataset(sql)
            Me.DGV_Master.DataSource = MasterDS.Tables(0)
            bFind = MasterDS.Tables(0).Rows.Count > 0
            SetGridRowBackColor(Me.DGV_Master, MasterDS)
            GetToolEnable()
        Catch ex As Exception
            MsgBox("PopupfrmQueryInfo:" & ex.Message, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

#End Region


#Region "interface"


    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        If AddEnable = False Then
            MessageBox.Show(My.Resources.NotAllowAdd, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        If IsClose = False Then
            MsgBox("當前期別已關賬，不能做入庫操作！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Exit Function
        End If
        Me.TabControl1.SelectedIndex = 1
        bBind = True
        ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd
        ClearText()
        SetCtlEnable(True)
        cbToStore_SelectedIndexChanged(Nothing, Nothing)
        MainForm.BtnEnable(False)
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel

        MainForm.BtnEnable(bFind)
        MainForm.ToolStripFilter.Enabled = False
        MainForm.ToolStripFind.Enabled = False
        MainForm.ToolStripImport.Enabled = False
        ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
        If Me.TabControl1.SelectedIndex = 0 Then
        ElseIf Me.TabControl1.SelectedIndex = 1 Then
            ClearText()
            SetCtlEnable(False)
            Me.cbFromStore.Enabled = False
            If MasterDS.Tables(0).Rows.Count <= 0 Then
                bFind = False
            Else
                bFind = True
                FillText(Me.DGV_Master.CurrentRow.Cells("BoNum").Value)
            End If
        Else
            Me.grpbox1.Enabled = False
        End If
        SetToolEnable()

    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

        Try
            If DeleteEnable = False Then
                MessageBox.Show(My.Resources.NotAllowDelete, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            Dim BoNum As String = Me.DGV_Master.CurrentRow.Cells("BoNum").Value
            If BoNum.Length > 0 Then
                If MsgBox(My.Resources.ConfirmDelete, MsgBoxStyle.Question + MsgBoxStyle.OkCancel, Msg.CompanyName) = MsgBoxResult.Ok Then
                    If DeleteDataset(BoNum) = True Then
                        Me.DGV_Master.DataSource = MasterDS.Tables(0)
                        MsgBox(My.Resources.DeleteSuccess, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        SetGridRowBackColor(Me.DGV_Master, MasterDS)
                        If Me.DGV_Master.Rows.Count > 0 Then
                            FillText(Me.DGV_Master.CurrentRow.Cells("BoNum").Value)
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("ActionDelete:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit
        If EditEnable = False Then
            MessageBox.Show(My.Resources.NotAllowEidt, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        If IsClose = False Then
            MsgBox("當前期別已關賬，不能操作！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Exit Function
        End If
        If Me.TabControl1.SelectedIndex = 0 Or Me.TabControl1.SelectedIndex = 1 Then
            SetCtlEnable(True)
            Me.TabControl1.SelectedIndex = 1
        Else
            Me.grpbox1.Enabled = True
        End If
        ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit
        cbToStore_SelectedIndexChanged(Nothing, Nothing)
        MainForm.BtnEnable(False)
    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport
        Select Case Me.TabControl1.SelectedIndex

            Case 0
                ExportToExcel(Me.DGV_Master, PubCompanyName)
            Case 1
                PrintInStoreNumDetail(Me.DGV_Detail, Me.LabInfo.Text, Me.cbInStoreType.Text, Me.cbToStore.Text, Me.cbFromStore.Text, Me.LabOperateDate.Text, Me.txtDeliverNo.Text, Me.txtDeliverPerson.Text, Me.DateTimePicker1.Value, "", 0)
        End Select

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter
        Try
            Dim Frm_Filter As New Frm_Filter
            Me.Cursor = Cursors.WaitCursor
            Frm_Filter.LoadHeaderCaption(Fields, "Frm_INTInStorage")
            Frm_Filter.ShowDialog()
            Me.Cursor = Cursors.Default
            ReBindGridCaption(Me.DGV_Master, "Frm_INTInStorage")
        Catch ex As Exception
            MsgBox("ActionFilter:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport
        Try
            If Me.cbInStoreType.SelectedIndex = 1 Then
                ExportPoNo(0)
            ElseIf Me.cbInStoreType.SelectedIndex = 2 Then
                ExportPoNo(1)
            ElseIf Me.cbInStoreType.SelectedIndex = 3 Then
                ExportPoNo(2)
            ElseIf Me.cbInStoreType.SelectedIndex = 4 Then
                ExportPoNo(3)
            End If
        Catch ex As Exception
            MsgBox("ActionImport:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

        Dim NewTable As DataTable = CType(Me.DGV_Detail.DataSource, DataTable)
        Dim sql As String
        Dim mHash As New Hashtable
        Dim m_DS As New DataSet
        Dim ds_Data As New DataSet
        Try

            If IsPlace = True Then
                sql = "select ID,fStorageId from BSC_Storage where fCode='" & Me.cbToStore.SelectedValue & "'"
                m_DS = ReturnDataset(sql)
            End If
            If Me.txtDeliverNo.Text.Length <= 0 Then
                MsgBox("送貨單號不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.txtDeliverNo.Focus()
                Return False
            End If
            If NewTable.Rows.Count <= 0 Then
                MsgBox("入庫數據為空，請確認！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.DGV_Detail.Focus()
                SendKeys.Send("{F4}")
                Return False
            End If
            Dim Period As String = Me.DateTimePicker1.Value.Year.ToString & Format(Me.DateTimePicker1.Value.Month, "00")
            Dim GetCurrentDate As String = Me.DateTimePicker1.Value.Year.ToString & "-" & Format(Me.DateTimePicker1.Value.Month, "00") & "-" & Format(Me.DateTimePicker1.Value.Day, "00")
            If PeriodData > Period Then
                MsgBox("送貨日期必須和當前期別一至！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.DateTimePicker1.Focus()
                SendKeys.Send("{F4}")
                Return False
            End If
            'If CDate(GetCurrentDate) > CDate(ServerDate) Then
            '    MsgBox("送貨日期不能大於當日期！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            '    Me.DateTimePicker1.Focus()
            '    SendKeys.Send("{F4}")
            '    Return False
            'End If
            For i As Integer = 0 To NewTable.Rows.Count - 1
                If IsPlace = True Then '' 如果倉庫控制到庫位，則一定要錄入批次，否則可輸可不輸 modify by huyang 2008-07-30
                    If NewTable.Rows(i).Item("BatchNo") Is System.DBNull.Value Or NewTable.Rows(i).Item("BatchNo").ToString = "" Then
                        MsgBox("第 [ " & i + 1 & " ] 行批次號不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(i).Cells("BatchNo")
                        Return False
                    End If
                End If

                If IsPlace = True Then
                    If NewTable.Rows(i).Item("StorePlace") Is System.DBNull.Value Or NewTable.Rows(i).Item("StorePlace").ToString = "" Then
                        MsgBox("第 [ " & i + 1 & " ] 行倉位不能為空！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(i).Cells("StorePlace")
                        Return False
                    Else
                        Dim Rows() As DataRow = m_DS.Tables(0).Select("fStorageId='" & NewTable.Rows(i).Item("StorePlace") & "'")
                        If Rows.Length <= 0 Then
                            MsgBox("倉位不正確或不存在此倉位,請重新輸入！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(i).Cells("StorePlace")
                            Return False
                        End If

                        Dim DatafVirtual As String = ""
                        Dim fBuJian As String = ""
                        Dim fIsTemp As Boolean
                        Dim GridBarCode As String = NewTable.Rows(i).Item("GoodsBarCode") & ""
                        Dim GridStorePlace As String = NewTable.Rows(i).Item("StorePlace") & ""
                        Dim GridBatch As String = NewTable.Rows(i).Item("BatchNo") & ""

                        Dim StoreRow() As DataRow = StoreageDS.Tables(0).Select("fStorageId='" & GridStorePlace & "'")
                        If StoreRow.Length > 0 Then
                            DatafVirtual = StoreRow(0).Item("fVirtual") & ""
                            fBuJian = StoreRow(0).Item("fBuJian") & ""
                            fIsTemp = CType(StoreRow(0).Item("fIsTemp"), Boolean)
                            If DatafVirtual = "1" Then
                                MsgBox("該倉位是壞貨倉位，不能將貨品放在此倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                Me.DGV_Detail.Focus()
                                Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("StorePlace")
                                Return False
                            Else
                                If fIsTemp = False Then
                                    Dim drRows() As DataRow = NewTable.Select("StorePlace='" & GridStorePlace & "'")
                                    If drRows.Length > 1 Then
                                        For Each mRow As DataRow In drRows
                                            If fBuJian = "1" Then
                                                If GridBarCode.ToLower <> mRow("GoodsBarCode").ToString.ToLower Then
                                                    MsgBox("錯誤：第 [" & i + 1 & "] 行.同一倉位下不能存放兩種貨品，請選擇其他倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                                    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(i).Cells("StorePlace")
                                                    Return False
                                                End If
                                            Else
                                                If GridBarCode.ToLower = mRow("GoodsBarCode").ToString.ToLower Then
                                                    If GridBatch.ToLower = mRow("BatchNo").ToString.ToLower Then
                                                    Else
                                                        MsgBox("錯誤：第 [" & i + 1 & "] 行.同一倉位下不能存放兩個批次，請選擇其他倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                                        Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(i).Cells("StorePlace")
                                                        Return False
                                                    End If
                                                Else
                                                    MsgBox("錯誤：第 [" & i + 1 & "] 行.同一倉位下不能存放兩種貨品，請選擇其他倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                                    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(i).Cells("StorePlace")
                                                    Return False
                                                End If
                                            End If
                                        Next
                                    End If

                                    sql = "select * from "
                                    sql += "(select Period,StoreHouse,replace(BarCode,'*','') as BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_Storequery where StoreHouse='" & PubCompanyCode & "' and StorePlace='" & GridStorePlace & "' group by StoreHouse,Period,barcode,Batch,StorePlace) a"
                                    sql += " where isnull(a.Goodsamount,0.00)>0"
                                    ds_Data = ReturnDataset(sql)
                                    If ds_Data.Tables(0).Rows.Count > 0 Then
                                        Dim BarCode As String = ds_Data.Tables(0).Rows(0).Item("BarCode") & ""
                                        Dim Batch As String = ds_Data.Tables(0).Rows(0).Item("Batch") & ""
                                        If fBuJian = "1" Then
                                            If String.Compare(GridBarCode, BarCode) <> 0 Then
                                                MsgBox("錯誤：第 [" & i + 1 & "] 行.同一倉位下不能存放兩種貨品，請選擇其他倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                                Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(i).Cells("StorePlace")
                                                Return False
                                            End If
                                        Else
                                            If String.Compare(GridBarCode, BarCode) = 0 Then
                                                If String.Compare(GridBatch, Batch) = 0 Then
                                                Else
                                                    MsgBox("錯誤：第 [" & i + 1 & "] 行.同一倉位下不能存放兩個批次，請選擇其他倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                                    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(i).Cells("StorePlace")
                                                    Return False
                                                End If
                                            Else
                                                MsgBox("錯誤：第 [" & i + 1 & "] 行.同一倉位下不能存放兩種貨品，請選擇其他倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                                Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(i).Cells("StorePlace")
                                                Return False
                                            End If
                                        End If
                                    End If
                                End If

                            End If
                        End If
                    End If
                End If
            Next
            Return True
        Catch ex As Exception
            MsgBox("ActionInitialize:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            mHash = Nothing
            ds_Data.Dispose()
            NewTable.Dispose()
            m_DS.Dispose()
            ds_Data = Nothing
            NewTable = Nothing
            m_DS = Nothing
        End Try
    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

        Dim mDs As DataSet

        Try
            If Me.DGV_Master.Rows.Count <= 0 Then
                MsgBox("對不起，沒有數據可列印！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Exit Function
            End If
            Dim Pathstr As String = ""
            Dim SubPathstr As String = ""
            Dim ConfigNode() As String = ReadConfigFile.Split(";")
            Dim mServer As String = ""
            Dim mDataBase As String = ""
            Dim mUserID As String = ""
            Dim mPassword As String = ""
            Dim sql As String = ""
            Dim BoNum As String = ""
            Dim PrintMode As String = String.Empty
            Dim PrintReportName As String = String.Empty

            If Me.TabControl1.SelectedIndex <> 2 Then
                'Pathstr = "D:\Reports\Store\InStoreReport.rpt"
                Pathstr = GetReportPath("Store", "InStoreReport.rpt")
            ElseIf Me.TabControl1.SelectedIndex = 2 Then
                PrintMode = InputBox("請選擇列印模式,默認為空時按照系統設置格式列印", "列印模式", "")
                PrintReportName = "RepElement" & PrintMode.ToString + ".rpt"
                Pathstr = GetReportPath("Store", PrintReportName)
            End If

            For i As Integer = 0 To ConfigNode.Length - 1
                If ConfigNode(i).Split("=")(0).ToLower = "Server".ToLower Then
                    mServer = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "DataBase".ToLower Then
                    mDataBase = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "Uid".ToLower Then
                    mUserID = ConfigNode(i).Split("=")(1)
                End If
                If ConfigNode(i).Split("=")(0).ToLower = "Pwd".ToLower Then
                    mPassword = ConfigNode(i).Split("=")(1)
                End If
            Next

            Dim myReportDoc As New CrystalDecisions.CrystalReports.Engine.ReportDocument
            Dim myParameterValues As New CrystalDecisions.Shared.ParameterValues
            Dim myDiscreteValue As New CrystalDecisions.Shared.ParameterDiscreteValue

            Dim logonInfo As New CrystalDecisions.Shared.TableLogOnInfo
            Dim table As CrystalDecisions.CrystalReports.Engine.Table
            myReportDoc.Load(Pathstr)

            For Each table In myReportDoc.Database.Tables
                logonInfo = table.LogOnInfo
                With logonInfo.ConnectionInfo
                    .ServerName = mServer
                    .DatabaseName = mDataBase
                    .UserID = mUserID
                    .Password = mPassword
                End With
                table.ApplyLogOnInfo(logonInfo)
            Next

            If Me.TabControl1.SelectedIndex <> 2 Then
                If Me.DGV_Master.SelectedRows.Count > 0 Then
                    For i As Integer = 0 To Me.DGV_Master.SelectedRows.Count - 1
                        BoNum += "''" & Me.DGV_Master.SelectedRows(i).Cells("BoNum").Value & "'',"
                    Next
                End If
                BoNum = BoNum.Remove(BoNum.Length - 1, 1)
                sql = "Exec Proc_ElementInStore '" & BoNum & "';"
            Else
                'sql = "select '*'+Element+'*' as Element,'S/N:'+Element as ElementNo "
                'sql += " from dbo.Stor_element where BoNumA='" & Me.txtBoNum.Text & "' and GoodsBarcode='*" & Me.txtbarcode.Text & "*'"
                sql = "select '*'+a.Element+'*' as Element,'S/N:'+a.Element as ElementNo,isnull(b.supperitem,'') as supperitem ,isnull(b.enname,'') as enname  "
                sql += " from dbo.Stor_element a ,bsc_goods b where a.BoNumA='" & Me.txtBoNum.Text & "' and  a.goodsbarcode=b.barcode"

            End If

            mDs = New DataSet
            mDs = ReturnDataset(sql)

            myReportDoc.SetDataSource(mDs.Tables(0))
            My.Forms.Frm_Report.CrystalReportViewer1.ReportSource = myReportDoc
            My.Forms.Frm_Report.CrystalReportViewer1.Zoom(1)
            My.Forms.Frm_Report.CrystalReportViewer1.DisplayGroupTree = False

            Frm_Report.ShowDialog()

        Catch ex As Exception
            MsgBox("對不起，打印出錯！" & ex.Message & ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            mDs = Nothing
        End Try

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        BtnActionSave()
        'isnull()
    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function

    Public Function ActionChecked() As Boolean
        Dim sql As String
        Dim mCount As Integer = 0
        Dim mCount1 As Integer = 0
        Dim mCount2 As Integer = 0
        Dim PoNum As String
        Dim m_Ds As New DataSet
        Dim ds_PoNum As DataSet
        Dim sqlConn As New SqlConnection
        Dim sqlcmd As New SqlCommand
        sqlConn = GetConn()
        If sqlConn.State = ConnectionState.Closed Then
            sqlConn.Open()
        End If
        Dim transqlserver As SqlTransaction = sqlConn.BeginTransaction
        Try
            If CheckEnable = False Then
                MessageBox.Show("對不起，您沒有審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            Dim BoNum As String = Me.DGV_Master.CurrentRow.Cells("BoNum").Value
            Dim CheckDate As String = ServerDate
            If BoNum.Length <= 0 Then Exit Function
            If MsgBox("確認審核此單嗎？", MsgBoxStyle.Information + MsgBoxStyle.OkCancel, Msg.CompanyName) = MsgBoxResult.Ok Then
                sql = "select * from Stor_TradeDetail where isnull(PoNum,null)<>'' and BoNum='" & BoNum & "'"
                ds_PoNum = ReturnDataset(sql)
                If ds_PoNum.Tables(0).Rows.Count > 0 Then

                    PoNum = ds_PoNum.Tables(0).Rows(0).Item("PoNum") & ""

                    sql = "select b.PoNum,b.PoNumItem,b.GoodsBarcode,Goodsamount=isnull(a.Goodsamount,0.00)+isnull(b.Goodsamount,0.00) from "
                    sql += "(select b.PoNum,b.PoNumItem,b.GoodsBarcode,sum(b.Goodsamount) as Goodsamount from Stor_TradeMaster a inner join Stor_TradeDetail b on a.boNum=b.BoNum where a.TradeType='+' and (a.BoStatus='B' Or a.BoStatus='F') and b.PoNum='" & PoNum & "' group by b.PoNum,b.PoNumItem,b.GoodsBarCode) a right join "
                    sql += "(select b.PoNum,b.PoNumItem,b.GoodsBarcode,b.Goodsamount from Stor_TradeMaster a inner join Stor_TradeDetail b on a.boNum=b.BoNum where a.TradeType='+' and isnull(b.PoNum,'')='" & PoNum & "' and a.BoNum='" & BoNum & "')b on a.PoNum=b.PoNum and a.PoNumItem=b.PoNumItem and a.GoodsBarcode=b.GoodsBarcode;"
                    sql += "select b.Num,b.SN,b.Barcode,b.Qty from Pur_POA a inner join Pur_POB b on a.Num=b.Num where a.BillStatusID='B' and b.Num='" & PoNum & "';"
                    sql += "select b.Num,b.SN,b.Barcode,b.Qty from Pur_POA a inner join Pur_POB b on a.Num=b.Num where b.Num='" & PoNum & "'"
                    m_Ds = ReturnDataset(sql)
                    If m_Ds.Tables(0).Rows.Count > 0 Then
                        If m_Ds.Tables(1).Rows.Count > 0 Then
                            For i As Int16 = 0 To m_Ds.Tables(0).Rows.Count - 1
                                Dim Goodsamount As Double = Convert.ToDouble(m_Ds.Tables(0).Rows(i).Item("Goodsamount"))
                                Dim PoNumItem As String = m_Ds.Tables(0).Rows(i).Item("PoNumItem") & ""
                                Dim BarCode As String = m_Ds.Tables(0).Rows(i).Item("GoodsBarCode") & ""
                                Dim DrRows() As DataRow = m_Ds.Tables(1).Select("Num='" & PoNum & "' and SN='" & PoNumItem & "' and Barcode='" & BarCode & "'")
                                If DrRows.Length > 0 Then
                                    Dim Qty As Double = Convert.ToDouble(DrRows(0).Item("Qty"))
                                    If Goodsamount = Qty Then
                                        mCount += 1
                                    End If
                                    If Goodsamount < Qty Then
                                        mCount1 += 1
                                    End If
                                    If Goodsamount > Qty Then
                                        mCount2 += 1
                                    End If
                                End If
                            Next
                        Else
                            If m_Ds.Tables(2).Rows.Count > 0 Then
                                MsgBox("對不起，該采購單據未審核或已移除，不能審核該單入庫！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                transqlserver.Rollback()
                                Exit Function
                            Else
                                sql = "UpDate Stor_TradeMaster Set BoStatus='B',CheckPerson='" & PubUserName & "',CheckDate='" & CheckDate & "',CheckComputer='" & My.Computer.Name & "' where BoNum='" & BoNum & "'"
                                With sqlcmd
                                    .Connection = sqlConn
                                    .Transaction = transqlserver
                                    .CommandType = CommandType.Text
                                    .CommandText = sql
                                    .ExecuteNonQuery()
                                End With
                            End If
                        End If
                        If mCount = m_Ds.Tables(0).Rows.Count Then
                            sql = "UpDate Stor_TradeMaster Set BoStatus='B',CheckPerson='" & PubUserName & "',CheckDate='" & CheckDate & "',CheckComputer='" & My.Computer.Name & "' where BoNum='" & BoNum & "';"
                            sql += "Update Pur_POA Set BillStatusID='F' where Num='" & PoNum & "'"
                            With sqlcmd
                                .Connection = sqlConn
                                .Transaction = transqlserver
                                .CommandType = CommandType.Text
                                .CommandText = sql
                                .ExecuteNonQuery()
                            End With
                        Else
                            If mCount2 > 0 Then
                                MsgBox("對不起，入庫數量與采購數量不一至，不能審核該單入庫！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                transqlserver.Rollback()
                                Exit Function
                            End If
                            If mCount1 > 0 Then
                                sql = "UpDate Stor_TradeMaster Set BoStatus='B',CheckPerson='" & PubUserName & "',CheckDate='" & CheckDate & "',CheckComputer='" & My.Computer.Name & "' where BoNum='" & BoNum & "'"
                                With sqlcmd
                                    .Connection = sqlConn
                                    .Transaction = transqlserver
                                    .CommandType = CommandType.Text
                                    .CommandText = sql
                                    .ExecuteNonQuery()
                                End With
                            End If
                        End If
                    End If
                Else
                    sql = "UpDate Stor_TradeMaster Set BoStatus='B',CheckPerson='" & PubUserName & "',CheckDate='" & CheckDate & "',CheckComputer='" & My.Computer.Name & "' where BoNum='" & BoNum & "'"
                    With sqlcmd
                        .Connection = sqlConn
                        .Transaction = transqlserver
                        .CommandType = CommandType.Text
                        .CommandText = sql
                        .ExecuteNonQuery()
                    End With
                End If
                Dim Rows() As DataRow = MasterDS.Tables(0).Select("BoNum='" & BoNum & "'")
                If Rows.Length > 0 Then
                    Rows(0).Item("BoStatus") = "核准"
                    Rows(0).Item("CheckPerson") = PubUserName
                    Rows(0).Item("CheckDate") = CheckDate
                End If
                MasterDS.AcceptChanges()
                Me.DGV_Master.DataSource = MasterDS.Tables(0)
                SetGridRowBackColor(Me.DGV_Master, MasterDS)
                MsgBox("謝謝,審核成功!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            End If
            transqlserver.Commit()
            sqlConn.Close()
        Catch ex As Exception
            transqlserver.Rollback()
            MsgBox("ActionChecked:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionUnchecked() As Boolean
        Dim sql As String
        Dim PoNum As String
        Dim m_Ds As New DataSet
        Try
            If UncheckEnable = False Then
                MessageBox.Show("對不起，您沒有反審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            Dim BoNum As String = Me.DGV_Master.CurrentRow.Cells("BoNum").Value
            Dim CheckDate As String = ServerDate
            If BoNum.Length <= 0 Then Exit Function
            If MsgBox("確認反審核此單嗎？", MsgBoxStyle.Information + MsgBoxStyle.OkCancel, Msg.CompanyName) = MsgBoxResult.Ok Then
                sql = "select * from Stor_TradeDetail where isnull(PoNum,null)<>'' and BoNum='" & BoNum & "'"
                m_Ds = ReturnDataset(sql)
                If m_Ds.Tables(0).Rows.Count > 0 Then
                    PoNum = m_Ds.Tables(0).Rows(0).Item("PoNum") & ""
                    sql = "Update Pur_POA set BillStatusID='B' where Num='" & PoNum & "'"
                    ReturnObject(sql)
                End If
                sql = "UpDate Stor_TradeMaster Set BoStatus='C',UnCheckPerson='" & PubUserName & "',UnCheckDate='" & CheckDate & "',UnCheckComputer='" & My.Computer.Name & "' where BoNum='" & BoNum & "'"
                ReturnObject(sql)
                Dim Rows() As DataRow = MasterDS.Tables(0).Select("BoNum='" & BoNum & "'")
                If Rows.Length > 0 Then
                    Rows(0).Item("BoStatus") = "反核准"
                    Rows(0).Item("CheckPerson") = PubUserName
                    Rows(0).Item("CheckDate") = CheckDate
                End If
                MasterDS.AcceptChanges()
                Me.DGV_Master.DataSource = MasterDS.Tables(0)
                SetGridRowBackColor(Me.DGV_Master, MasterDS)
                MsgBox("謝謝,反核准成功!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            End If

        Catch ex As Exception
            MsgBox("ActionUnchecked:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionComplete() As Boolean
        Try

        Catch ex As Exception
            MsgBox("ActionComplete:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function
#End Region


#Region "Sub or function"

    Private Sub BindGridMaster()
        Dim mTable As New DataTable
        Try

            With mTable
                .Columns.Add("BoNum")
                .Columns.Add("TradeType")
                .Columns.Add("InOrOutType")
                .Columns.Add("ToStore")
                .Columns.Add("FromStore")
                .Columns.Add("StorePlace")
                .Columns.Add("DeliverNo")
                .Columns.Add("DeliverPerson")
                .Columns.Add("DeliverDate")
                .Columns.Add("DeliverCar")
                .Columns.Add("Batch")
                .Columns.Add("BoStatus")
                .Columns.Add("Remark")
                .Columns.Add("OperatePerson")
                .Columns.Add("OperateDate")
                .Columns.Add("CheckPerson")
                .Columns.Add("CheckDate")
                .Columns.Add("PoNum")
                .Columns.Add("Date")
            End With
            MasterDS = New DataSet
            MasterDS.Tables.Add(mTable)
            Me.DGV_Master.DataSource = MasterDS.Tables(0)

            With Me.DGV_Master
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHash(0).Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                    '.Columns(i).SortMode = DataGridViewColumnSortMode.NotSortable
                Next
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .ReadOnly = True
                .MultiSelect = True
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            End With
        Catch ex As Exception
            MsgBox("BindGridMaster:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            mTable.Dispose()
            mTable = Nothing
        End Try
    End Sub

    Private Sub BindDataGridView()
        Dim mTable As New DataTable
        Try

            With mTable
                .Columns.Add("ItemNo")
                .Columns.Add("PoNum")
                .Columns.Add("PoNumItem")
                .Columns.Add("GoodsBarCode")
                .Columns.Add("GoodsCode")
                .Columns.Add("ENName")
                .Columns.Add("SupperItem")
                .Columns.Add("GoodsName")
                .Columns.Add("GoodsColor")
                .Columns.Add("GoodsSpec")
                .Columns.Add("QTy")
                .Columns.Add("Goodsamount", GetType(Decimal))
                .Columns.Add("BatchNo")
                .Columns.Add("StorePlace")
                .Columns.Add("GoodsOther")
                .Columns.Add("PackingNum")
            End With
            DetailDS = New DataSet
            DetailDS.Tables.Add(mTable)
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)

            With Me.DGV_Sum
                .ReadOnly = True
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                Me.DGV_Sum.Columns.Add("ItemNo", "")
                Me.DGV_Sum.Columns.Add("PoNum", "")
                Me.DGV_Sum.Columns.Add("PoNumItem", "")
                Me.DGV_Sum.Columns.Add("GoodsBarCode", "")
                Me.DGV_Sum.Columns.Add("GoodsCode", "")
                Me.DGV_Sum.Columns.Add("ENName", "")
                Me.DGV_Sum.Columns.Add("SupperItem", "")
                Me.DGV_Sum.Columns.Add("GoodsName", "")
                Me.DGV_Sum.Columns.Add("GoodsColor", "")
                Me.DGV_Sum.Columns.Add("GoodsSpec", "")
                Me.DGV_Sum.Columns.Add("QTy", "")
                Me.DGV_Sum.Columns.Add("Goodsamount", "")
                Me.DGV_Sum.Columns.Add("BatchNo", "")
                Me.DGV_Sum.Columns.Add("StorePlace", "")
                Me.DGV_Sum.Columns.Add("GoodsOther", "")
                Me.DGV_Sum.Columns.Add("PackingNum", "")
                .Columns("GoodsBarCode").Visible = True
                .Columns("QTy").Visible = False
                .Columns("Goodsamount").DefaultCellStyle.BackColor = Color.AliceBlue
                .Columns("Goodsamount").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("ItemNo").Width = 55
                Dim GridRow As New DataGridViewRow
                Me.DGV_Sum.Rows.Add(GridRow)
            End With


            With Me.DGV_Detail
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHash(1).Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                    If .Columns(i).Name.ToLower = "ItemNo".ToLower Or .Columns(i).Name.ToLower = "SupperItem".ToLower Then
                        .Columns(i).SortMode = DataGridViewColumnSortMode.Automatic
                    Else
                        .Columns(i).SortMode = DataGridViewColumnSortMode.NotSortable
                    End If
                Next

                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                '.SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .MultiSelect = False
                .Columns("Goodsamount").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("QTy").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("QTy").DefaultCellStyle.BackColor = System.Drawing.SystemColors.Info
                .Columns("Goodsamount").DefaultCellStyle.BackColor = Color.AliceBlue
                .Columns("BatchNo").DefaultCellStyle.BackColor = Color.AliceBlue
                .Columns("GoodsBarCode").Visible = True
                .Columns("QTy").Visible = False
                .Columns("QTy").ReadOnly = True
                .Columns("ItemNo").ReadOnly = True
                .Columns("ItemNo").Width = 55
            End With

            SetGridWidth()
        Catch ex As Exception
            MsgBox("BindDataGridView:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            mTable.Dispose()
            mTable = Nothing
        End Try
    End Sub

    Private Sub BindElementGridView()
        Dim mTable As New DataTable
        Try
            With mTable
                .Columns.Add("Element")
                .Columns.Add("Elementamount")
                .Columns.Add("ElementUnit")
                .Columns.Add("Elementbatch")
                .Columns.Add("StorePlace")
                .Columns.Add("ElementStatus")
            End With

            Me.dgv_Element.DataSource = mTable

            With Me.dgv_Element
                With Me.dgv_Element
                    For i As Integer = 0 To .Columns.Count - 1
                        Dim mKey As String = .Columns(i).Name
                        Dim CaptionStr As String = BindHash(2).Item(mKey)
                        .Columns(i).HeaderText = CaptionStr
                    Next
                    .AllowUserToAddRows = False
                    .AllowUserToDeleteRows = False
                    .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                End With
            End With
        Catch ex As Exception
            MsgBox("BindElementGridView:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            mTable.Dispose()
            mTable = Nothing
        End Try

    End Sub

    Private Function BindHash(Optional ByVal index As Integer = 0) As Hashtable
        Try
            Dim mHash As New Hashtable
            With mHash
                Select Case index
                    Case 0
                        .Add("BoNum", "入庫單號")
                        .Add("TradeType", "庫存操作")
                        .Add("InOrOutType", "入庫類型")
                        .Add("ToStore", "目的倉庫")
                        .Add("FromStore", "源倉庫")
                        .Add("StorePlace", "倉位")
                        .Add("DeliverNo", "送貨單號")
                        .Add("DeliverPerson", "負責人員")
                        .Add("DeliverDate", "送貨日期")
                        .Add("DeliverCar", "車牌號碼")
                        .Add("Batch", "批次號碼")
                        .Add("BoStatus", "單據狀態")
                        .Add("Remark", "備注")
                        .Add("OperatePerson", "操作人員")
                        .Add("OperateDate", "操作日期")
                        .Add("CheckPerson", "審核人員")
                        .Add("CheckDate", "審核日期")
                        .Add("PoNum", "采購單號")
                        .Add("Date", "采購日期")
                    Case 1
                        .Add("ItemNo", "編號")
                        .Add("PoNum", "文件號")
                        .Add("PoNumItem", "項目編號")
                        .Add("GoodsBarCode", "貨品條碼")
                        .Add("GoodsCode", "貨品編號")
                        .Add("ENName", "英文名")
                        .Add("SupperItem", "廠商產品編號")
                        .Add("GoodsName", "貨品名稱")
                        .Add("GoodsColor", "貨品顏色")
                        .Add("GoodsSpec", "貨品規格")
                        .Add("QTy", "采購數量")
                        .Add("Goodsamount", "貨品數量")
                        .Add("BatchNo", "批次號")
                        .Add("StorePlace", "存儲倉位")
                        .Add("GoodsOther", "備注")
                        .Add("PackingNum", "件數")
                    Case 2
                        .Add("Element", "元件號")
                        .Add("Elementamount", "元件數量")
                        .Add("ElementUnit", "單位")
                        .Add("Elementbatch", "批次")
                        .Add("StorePlace", "庫位")
                        .Add("ElementStatus", "狀態")
                End Select
            End With
            Return mHash
        Catch ex As Exception
            MsgBox("BindHash:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Return Nothing
        End Try
    End Function

    Private Sub SetGridWidth()

        Try
            For i As Integer = 0 To Me.DGV_Detail.Columns.Count - 1
                Me.DGV_Sum.Columns(i).Width = Me.DGV_Detail.Columns(i).Width
            Next
        Catch ex As Exception
            MsgBox("SetGridWidth:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub LoadStorePlace()

        Try
            Dim sql As String
            Dim mNode As New TreeNode
            Dim Nodes As TreeNode
            'sql = "select ID,fCode,fStorageID,fVirtual,fBuJian,isnull(fIsTemp,0) as fIsTemp from dbo.BSC_Storage where fCode='" & PubCompanyCode & "' order by fStorageID"
            sql = "select ID,fCode,fStorageID,fVirtual,fBuJian,isnull(fIsTemp,0) as fIsTemp,isnull(n.Goodsamount,0.00) as Goodsamount from dbo.BSC_Storage m left join ("
            sql += "select distinct(a.StorePlace),Goodsamount from "
            sql += " (select Period,StoreHouse,StorePlace,sum(Goodsamount) as Goodsamount from V_Storequery where StoreHouse='" & PubCompanyCode & "' group by StoreHouse,Period,StorePlace) a "
            sql += " left join BSC_Storage b on a.Storeplace=b.fStorageId  where isnull(b.fIsTemp,0)<>1 and isnull(a.Goodsamount,0.00)>0) n on m.fStorageID=n.StorePlace where fCode='" & PubCompanyCode & "' order by fStorageID"

            StoreageDS = New DataSet
            StoreageDS = ReturnDataset(sql)
            mNode.Tag = PubCompanyCode
            mNode.Text = PubCompanyName
            mNode.Expand()
            SelectNode = mNode
            Me.TreeView1.Nodes.Add(mNode)
            For Each mRow As DataRow In StoreageDS.Tables(0).Rows
                Nodes = New TreeNode
                If mRow("Goodsamount") = 0.0 Then
                    Nodes.BackColor = Color.DarkGray
                End If
                Nodes.Tag = mRow("ID") & ""
                Nodes.Text = mRow("fStorageID") & ""
                mNode.Nodes.Add(Nodes)
            Next
        Catch ex As Exception
            MsgBox("LoadStorePlace:" & ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub LoadGoods()
        Try
            Dim sql As String
            sql = "select replace(a.Barcode,'*','') as BarCode,a.Code,isnull(a.enname,'') as enname,a.Cnname,a.SupperItem,b.ColorCName as Color,c.SizeSName as Spec,a.IsElement,isnull(packingnum,1)as PackingNum from BSC_Goods a inner join BSC_ColorDefine b on a.Color=b.Colorcode inner join BSC_SizeDefine c on a.Spec=c.Sizecode"
            GoodsDS = New DataSet
            GoodsDS = ReturnDataset(sql)

            Me.ComBo.DisplayMember = "Barcode"
            Me.ComBo.ValueMember = "Barcode"
            Me.ComBo.DataSource = GoodsDS.Tables(0)
        Catch ex As Exception
            MsgBox("LoadGoods:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub LoadStoreType()
        Dim mTable As DataTable
        Dim nTable As DataTable
        Try
            Dim sql As String
            sql = "select * from dbo.Stor_tradecode; "
            sql += "select b.* from BSC_OtherDefineA a inner join BSC_OtherDefineB b on a.ID=b.ItemNo where a.ItemCode='InStoreType';"
            sql += "select * from dbo.BSC_StoreHouse where fStatus=0 ;"
            sql += "select * From dbo.BSC_StoreHouse;"
            sql += "select b.* from BSC_OtherDefineA a inner join BSC_OtherDefineB b on a.ID=b.ItemNo where a.ItemCode='BillstatusDefine';"
            sql += "select * from dbo.BSC_Employee where fDeptID in (select ID from BSC_DEPT where fCode='" & PubCompanyCode & "');"
            StoreDS = New DataSet
            StoreDS = ReturnDataset(sql)

            Me.cbTradeCode.DisplayMember = "Name"
            Me.cbTradeCode.ValueMember = "AddOrNot"
            Me.cbTradeCode.DataSource = StoreDS.Tables(0)
            Me.cbTradeCode.DropDownStyle = ComboBoxStyle.DropDownList
            Me.cbTradeCode.SelectedIndex = 0
            Me.cbTradeCode.Enabled = False

            Me.cbInStoreType.DisplayMember = "ListA"
            Me.cbInStoreType.ValueMember = "Listcode"
            Me.cbInStoreType.DataSource = StoreDS.Tables(1)
            Me.cbInStoreType.DropDownStyle = ComboBoxStyle.DropDownList

            Me.cbFromStore.DisplayMember = "fShortName"
            Me.cbFromStore.ValueMember = "fCode"
            Me.cbFromStore.DataSource = StoreDS.Tables(2)
            Me.cbFromStore.DropDownStyle = ComboBoxStyle.DropDownList
            Me.cbFromStore.Enabled = False


            Me.cbToStore.DisplayMember = "fShortName"
            Me.cbToStore.ValueMember = "fCode"
            Me.cbToStore.DataSource = StoreDS.Tables(3)
            'Me.cbToStore.DropDownStyle = ComboBoxStyle.DropDownList
            Me.cbToStore.SelectedIndex = Me.cbToStore.FindString(PubCompanyName)

            Me.txtStore.DisplayMember = "fShortName"
            Me.txtStore.ValueMember = "fCode"
            Me.txtStore.DataSource = StoreDS.Tables(3)
            Me.txtStore.SelectedIndex = -1

            nTable = CType(Me.cbInStoreType.DataSource, DataTable)
            Me.txtStoreType.DisplayMember = "ListA"
            Me.txtStoreType.ValueMember = "Listcode"
            Me.txtStoreType.DataSource = nTable

            Me.cmbStatus.DisplayMember = "ListA"
            Me.cmbStatus.ValueMember = "Listcode"
            Me.cmbStatus.DataSource = StoreDS.Tables(4)
            Me.cmbStatus.DropDownStyle = ComboBoxStyle.DropDownList
            Me.cmbStatus.SelectedIndex = 0
            Me.cmbStatus.Enabled = False

            mTable = CType(Me.cmbStatus.DataSource, DataTable)
            Me.txtBoStatus.DisplayMember = "ListA"
            Me.txtBoStatus.ValueMember = "Listcode"
            Me.txtBoStatus.DataSource = mTable
            Me.txtBoStatus.SelectedIndex = -1

            Me.txtStorePlace.DisplayMember = "fCName"
            Me.txtStorePlace.ValueMember = "fCode"
            Me.txtStorePlace.DataSource = StoreDS.Tables(5)
            Me.txtStorePlace.SelectedIndex = -1
        Catch ex As Exception
            MsgBox("LoadStoreType:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            'StoreDS.Tables(0).Dispose()
            'StoreDS.Tables(2).Dispose()
            'StoreDS.Tables(4).Dispose()
            'StoreDS.Tables(5).Dispose()
            mTable = Nothing
            nTable = Nothing
        End Try
    End Sub

    Private Sub ExportPoNo(ByVal index As Integer)
        Try
            Dim Frm_ExportData As New Frm_ExportData
            Frm_ExportData.LoadFirstTree(index)
            Frm_ExportData.ShowDialog()
            Dim GetPoNum As String
            Dim PoNum As String = ""
            Dim sql As String = ""
            GetPoNum = Frm_ExportData.LabPoNum.Text
            If GetPoNum.Length <= 0 Then Exit Sub
            If GetPoNum.Length > 0 Then
                If GetPoNum.StartsWith("^") Then
                    GetPoNum = GetPoNum.Remove(0, 1)
                End If
                If GetPoNum.EndsWith("^") Then
                    GetPoNum = GetPoNum.Remove(GetPoNum.Length - 1, 1)
                End If
                For i As Integer = 0 To GetPoNum.Split("^").Length - 1
                    PoNum += "'" & GetPoNum.Split("^")(i) & "',"
                Next
            End If

            If PoNum.Length > 0 Then
                If PoNum.EndsWith(",") Then
                    PoNum = PoNum.Remove(PoNum.Length - 1, 1)
                End If
            End If
            Me.txtRemark.Text = Replace(PoNum.ToString, "'", "")
            Select Case index
                Case 0
                    sql = "select ItemNo='',* into #BB from V_GetCheckedPoNum where PoNum in(" & PoNum & ");"
                    sql += "select * from #BB where isnull(Goodsamount,0.00)>0 order by PoNumItem;"
                    sql += "drop table #BB;"
                Case 1
                    sql = "Select ItemNo,PoNum,PoNumItem,GoodsBarcode,GoodsCode,SupperItem,GoodsName,GoodsColor,GoodsSpec,Qty=0,Goodsamount,BatchNo,StorePlace,GoodsOther into #BB from V_GetCheckedBoNum where BoNum in(" & PoNum & ");"
                    sql += "select * from #BB order by PoNum,PoNumItem;"
                    sql += "drop table #BB"
                Case 2
                    sql = "Select ItemNo,PoNum,PoNumItem,GoodsBarcode,GoodsCode,SupperItem,GoodsName,GoodsColor,GoodsSpec,Qty=0,Goodsamount,BatchNo,StorePlace,GoodsOther into #BB from V_GetCheckedBoNum where BoNum in(" & PoNum & ");"
                    sql += "select * from #BB order by PoNum,PoNumItem;"
                    sql += "drop table #BB"
                Case 3
                    sql = "Select ItemNo,PoNum,PoNumItem,GoodsBarcode,GoodsCode,SupperItem,GoodsName,GoodsColor,GoodsSpec,Qty=0,Goodsamount,BatchNo,StorePlace,GoodsOther into #BB from V_SaleOrde_POS where PoNum in(" & PoNum & ");"
                    sql += "select * from #BB order by PoNum,PoNumItem;"
                    sql += "drop table #BB"
            End Select

            DetailDS = ReturnDataset(sql)
            Select Case index
                Case 0
                    If DetailDS.Tables(0).Rows.Count <= 0 Then
                        MsgBox("該采購單已入庫，不能重複操作！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    End If
                Case 1
                Case 2
            End Select
            For i As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                DetailDS.Tables(0).Rows(i).Item("ItemNo") = Format(i + 1, "000")
            Next
            DetailDS.AcceptChanges()
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
            If index <> 0 Then
                Me.DGV_Detail.Columns("Qty").Visible = False
            End If

        Catch ex As Exception
            MsgBox("ExportPoNo:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Function ReturnTable(ByVal BoNum As String, Optional ByVal index As Integer = 0) As DataTable
        Try
            Select Case index
                Case 0
                    Dim nTable As New DataTable
                    With nTable
                        .Columns.Add("BoNum")
                        .Columns.Add("ItemNo")
                        .Columns.Add("PoNum")
                        .Columns.Add("PoNumItem")
                        .Columns.Add("DeliverNo")
                        .Columns.Add("GoodsBarCode")
                        .Columns.Add("Batch")
                        .Columns.Add("GoodsStatus")
                        .Columns.Add("StorePlace")
                        .Columns.Add("Goodsamount")
                        .Columns.Add("GoodsOther")
                    End With

                    For Each Row As DataRow In DetailDS.Tables(0).Rows
                        Dim mRow As DataRow = nTable.NewRow
                        mRow("BoNum") = BoNum
                        mRow("ItemNo") = Row("ItemNo") & ""
                        mRow("PoNum") = Row("PoNum") & ""
                        mRow("PoNumItem") = Row("PoNumItem") & ""
                        mRow("DeliverNo") = Me.txtDeliverNo.Text
                        mRow("GoodsBarCode") = "*" & Row("GoodsBarCode") & "*"
                        mRow("Batch") = Row("BatchNo") & ""
                        mRow("GoodsStatus") = 1
                        mRow("StorePlace") = Row("StorePlace") & ""
                        mRow("Goodsamount") = Row("Goodsamount") & ""
                        mRow("GoodsOther") = Row("GoodsOther") & ""
                        nTable.Rows.Add(mRow)
                    Next
                    nTable.AcceptChanges()
                    Return nTable
                Case 1
                    Dim NewTable As New DataTable
                    With NewTable
                        .Columns.Add("BoNumA")
                        .Columns.Add("GoodsBarCode")
                        .Columns.Add("Element")
                        .Columns.Add("EleMentamount")
                        .Columns.Add("ElementUnit")
                        .Columns.Add("Elementbatch")
                        .Columns.Add("StorePlace")
                        .Columns.Add("ElementStatus")
                    End With

                    If Me.dgv_Element.Rows.Count > 0 Then
                        For i As Int16 = 0 To Me.dgv_Element.Rows.Count - 1
                            Dim mRow As DataRow = NewTable.NewRow

                            mRow("BoNumA") = BoNum
                            If Me.txtbarcode.Text.ToString.Length > 0 Then
                                mRow("GoodsBarCode") = "*" & Me.txtbarcode.Text & "*"
                            Else
                                mRow("GoodsBarCode") = ""
                            End If

                            mRow("Element") = Me.dgv_Element.Rows(i).Cells("Element").Value
                            mRow("EleMentamount") = Me.dgv_Element.Rows(i).Cells("Elementamount").Value
                            mRow("ElementUnit") = Me.dgv_Element.Rows(i).Cells("ElementUnit").Value
                            mRow("Elementbatch") = Me.dgv_Element.Rows(i).Cells("ElementBatch").Value
                            mRow("StorePlace") = Me.dgv_Element.Rows(i).Cells("StorePlace").Value
                            mRow("ElementStatus") = Me.dgv_Element.Rows(i).Cells("ElementStatus").Value
                            NewTable.Rows.Add(mRow)
                        Next
                        NewTable.AcceptChanges()
                    End If
                    Return NewTable
                Case 2
                    Dim NewTable As New DataTable
                    With NewTable
                        .Columns.Add("ID")
                        .Columns.Add("storehouse")
                        .Columns.Add("barcode")
                        .Columns.Add("element")
                        .Columns.Add("qty")
                        .Columns.Add("unit")
                        .Columns.Add("elementbatch")
                        .Columns.Add("place")
                        .Columns.Add("status")
                    End With

                    'If Me.DataGridView1.Rows.Count > 0 Then
                    For i As Int16 = 0 To Me.dgv_Element.Rows.Count - 1
                        Dim NewRow As DataRow = NewTable.NewRow
                        '存入倉庫名稱
                        '如果是根據單號生成的元件則有倉庫名稱
                        '否則為空，等到掃描確認的時候再更新此元件的倉庫
                        If Me.dgv_Element.RowCount > 0 Then
                            '    NewRow("storehouse") = BoNum.Substring(0, 2)
                            'Else
                            NewRow("storehouse") = ""
                        End If

                        If Me.txtbarcode.Text.ToString.Length > 0 Then
                            NewRow("barcode") = "*" & Me.txtbarcode.Text & "*"
                        Else
                            NewRow("barcode") = ""
                        End If
                        NewRow("element") = Me.dgv_Element.Rows(i).Cells("Element").Value
                        NewRow("qty") = Me.dgv_Element.Rows(i).Cells("Elementamount").Value
                        NewRow("elementbatch") = Me.dgv_Element.Rows(i).Cells("ElementBatch").Value
                        NewRow("place") = Me.dgv_Element.Rows(i).Cells("StorePlace").Value
                        NewRow("status") = Me.dgv_Element.Rows(i).Cells("ElementStatus").Value
                        NewRow("unit") = Me.dgv_Element.Rows(i).Cells("ElementUnit").Value
                        NewTable.Rows.Add(NewRow)
                    Next

                    NewTable.AcceptChanges()
                    Return NewTable
            End Select

        Catch ex As Exception
            MsgBox("ReturnTable:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Return Nothing
        End Try
    End Function

    Private Sub BtnActionSave()

        If ActionInitialize() = False Then Exit Sub
        Dim sqlConn As New SqlConnection
        Dim sqlcmd As New SqlCommand
        Dim SqlBulk As SqlClient.SqlBulkCopy
        Dim sql As String
        Dim TradeType As String = Me.cbTradeCode.SelectedValue.ToString
        Dim InOrOutType As String = Me.cbInStoreType.SelectedValue.ToString
        Dim ToStore As String = Me.cbToStore.SelectedValue.ToString
        Dim FromStore As String
        Dim OrdeStatus As String = Me.cmbStatus.SelectedValue.ToString
        Dim txtDeliverNo As String = Me.txtDeliverNo.Text
        Dim txtDeliverDate As String = Me.DateTimePicker1.Value.Year & "-" & Format(Me.DateTimePicker1.Value.Month, "00") & "-" & Format(Me.DateTimePicker1.Value.Day, "00")
        Dim txtDeliverCar As String = Me.txtCarNo.Text
        Dim txtDeliverPerson As String = Me.txtDeliverPerson.Text
        Dim Remark As String = Me.txtRemark.Text

        sqlConn = GetConn()
        If sqlConn.State = ConnectionState.Closed Then
            sqlConn.Open()
        End If
        Dim transqlserver As SqlTransaction = sqlConn.BeginTransaction
        Try
            If Me.cbFromStore.Enabled = True Then
                FromStore = Me.cbFromStore.SelectedValue.ToString
            Else
                FromStore = ""
            End If

            If Me.TabControl1.SelectedIndex = 1 Then
                If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then

                    Dim BoNum As String = AutoCreateBoNum(PubCompanyCode, Me.cbTradeCode.SelectedValue, Me.cbToStore.SelectedValue, "Stor_TradeMaster")

                    sql = "Insert Into Stor_TradeMaster(BoNum,TradeType,InOrOutType,ToStore,FromStore,DeliverNo,DeliverPerson,DeliverDate,DeliverCar,BoStatus,Remark,OperatePerson,OPerateComputer) values('"
                    sql += BoNum & "','" & TradeType & "','" & InOrOutType & "','" & ToStore & "','" & FromStore & "','" & txtDeliverNo & "','" & txtDeliverPerson & "','" & txtDeliverDate & "','" & txtDeliverCar & "','" & OrdeStatus & "','" & Remark & "','" & PubUserName & "','" & My.Computer.Name & "')"
                    With sqlcmd
                        .Connection = sqlConn
                        .Transaction = transqlserver
                        .CommandType = CommandType.Text
                        .CommandText = sql
                        .ExecuteNonQuery()
                    End With

                    Dim mTable As DataTable = ReturnTable(BoNum, 0)
                    SqlBulk = New SqlClient.SqlBulkCopy(sqlConn, SqlBulkCopyOptions.Default, transqlserver)
                    SqlBulk.DestinationTableName = "Stor_TradeDetail"
                    SqlBulk.BulkCopyTimeout = 100
                    SqlBulk.WriteToServer(mTable)

                    Me.LabInfo.Text = BoNum
                    AddDataset(BoNum, Me.cbTradeCode.Text, Me.cbInStoreType.Text, Me.cbToStore.Text, Me.cbFromStore.Text, txtDeliverNo, txtDeliverPerson, txtDeliverDate, txtDeliverCar, 1, Remark, PubUserName, Format(Now.Date, "yyyy-MM-dd"))
                    mTable.Dispose()
                Else
                    sql = "Update Stor_TradeMaster Set InOrOutType='" & InOrOutType & "',ToStore='" & ToStore & "',FromStore='" & FromStore & "',DeliverNo='" & txtDeliverNo & "',DeliverPerson='" & txtDeliverPerson & "',DeliverDate='" & txtDeliverDate & "',DeliverCar='" & txtDeliverCar & "',Remark='" & Remark & "',UpdatePerson='" & PubUserName & "',UpdateDate=getdate(),UpdateComputer='" & My.Computer.Name
                    sql += "'  where BoNum='" & Me.LabInfo.Text & "' ;"
                    sql += " Delete Stor_TradeDetail where BoNum='" & Me.LabInfo.Text & "'"
                    With sqlcmd
                        .Connection = sqlConn
                        .Transaction = transqlserver
                        .CommandType = CommandType.Text
                        .CommandText = sql
                        .ExecuteNonQuery()
                    End With

                    Me.DGV_Detail.Update()
                    Dim mTable As DataTable = ReturnTable(Me.LabInfo.Text, 0)
                    SqlBulk = New SqlClient.SqlBulkCopy(sqlConn, SqlBulkCopyOptions.Default, transqlserver)
                    SqlBulk.DestinationTableName = "Stor_TradeDetail"
                    SqlBulk.BulkCopyTimeout = 100
                    SqlBulk.WriteToServer(mTable)
                    EditDataSet(Me.LabInfo.Text, Me.cbTradeCode.Text, Me.cbInStoreType.Text, Me.cbToStore.Text, Me.cbFromStore.Text, txtDeliverNo, txtDeliverPerson, txtDeliverDate, txtDeliverCar, 1, Remark, PubUserName, Format(Now.Date, "yyyy-MM-dd"))
                    mTable.Dispose()
                End If
            ElseIf Me.TabControl1.SelectedIndex = 2 Then
                If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                ElseIf ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                    sql = "Delete Stor_element where BoNumA='" & Me.LabInfo.Text & "' and GoodsBarCode='*" & Me.txtbarcode.Text & "*'"
                    ReturnObject(sql)
                    Dim mTable As DataTable = ReturnTable(Me.txtBoNum.Text, 1)
                    SqlBulk = New SqlClient.SqlBulkCopy(sqlConn, SqlBulkCopyOptions.Default, transqlserver)
                    SqlBulk.DestinationTableName = "Stor_element"
                    SqlBulk.BulkCopyTimeout = 100
                    SqlBulk.WriteToServer(mTable)
                    Dim lsvItemCount As Integer = Me.dgv_Element.Rows.Count
                    sql = "update number  set  number= number +" & lsvItemCount & " where  billtype= 'element'"
                    With sqlcmd
                        .Connection = sqlConn
                        .Transaction = transqlserver
                        .CommandType = CommandType.Text
                        .CommandText = sql
                        .ExecuteNonQuery()
                    End With
                    mTable.Dispose()
                End If
                Me.grpbox1.Enabled = False
            End If

            transqlserver.Commit()
            sqlConn.Close()

            MsgBox(IIf(ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd, My.Resources.AddSuccess, My.Resources.EditSuccess), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Me.DGV_Master.DataSource = MasterDS.Tables(0)
            Me.DGV_Master.CurrentCell = Me.DGV_Master.Rows(Me.DGV_Master.Rows.Count - 1).Cells("BoNum")
            SetGridRowBackColor(Me.DGV_Master, MasterDS)
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            SetCtlEnable(False)
            bFind = True
            MainForm.BtnEnable(bFind)
        Catch ex As Exception
            transqlserver.Rollback()
            MsgBox("BtnActionSave:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub AddDataset(ByVal BoNum As String, ByVal TradeType As String, ByVal InOrOutType As String, ByVal ToStore As String, ByVal FromStore As String, ByVal DeliverNo As String, ByVal DeliverPerson As String, _
                          ByVal DeliverDate As String, ByVal DeliverCar As String, ByVal BoStatus As String, ByVal Remark As String, ByVal OperatePerson As String, ByVal OperateDate As String)
        Try
            Dim mRow As DataRow = MasterDS.Tables(0).NewRow
            mRow("BoNum") = BoNum
            mRow("TradeType") = TradeType
            mRow("InOrOutType") = InOrOutType
            mRow("ToStore") = ToStore
            If cbFromStore.SelectedIndex <> 3 Then
                mRow("FromStore") = ""
            Else
                mRow("FromStore") = FromStore
            End If
            mRow("DeliverNo") = DeliverNo
            mRow("DeliverPerson") = DeliverPerson
            mRow("DeliverDate") = DeliverDate
            mRow("DeliverCar") = DeliverCar
            mRow("BoStatus") = "保存"
            mRow("Remark") = Remark
            mRow("OperatePerson") = OperatePerson
            mRow("OperateDate") = OperateDate
            MasterDS.Tables(0).Rows.Add(mRow)
            MasterDS.AcceptChanges()

        Catch ex As Exception
            MsgBox("AddDataset:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub EditDataSet(ByVal BoNum As String, ByVal TradeType As String, ByVal InOrOutType As String, ByVal ToStore As String, ByVal FromStore As String, ByVal DeliverNo As String, ByVal DeliverPerson As String, _
                          ByVal DeliverDate As String, ByVal DeliverCar As String, ByVal BoStatus As String, ByVal Remark As String, ByVal OperatePerson As String, ByVal OperateDate As String)
        Try
            Dim Rows() As DataRow = MasterDS.Tables(0).Select("BoNum='" & BoNum & "'")
            If Rows.Length > 0 Then
                Rows(0).Item("TradeType") = TradeType
                Rows(0).Item("InOrOutType") = InOrOutType
                Rows(0).Item("ToStore") = ToStore
                Rows(0).Item("FromStore") = FromStore
                Rows(0).Item("DeliverNo") = DeliverNo
                Rows(0).Item("DeliverPerson") = DeliverPerson
                Rows(0).Item("DeliverDate") = DeliverDate
                Rows(0).Item("DeliverCar") = DeliverCar
                Rows(0).Item("BoStatus") = "保存"
                Rows(0).Item("Remark") = Remark
                'Rows(0).Item("UpdatePerson") = OperatePerson
                'Rows(0).Item("UpdateDate") = OperateDate
                MasterDS.AcceptChanges()
            End If

        Catch ex As Exception
            MsgBox("EditDataSet:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Function DeleteDataset(ByVal BoNum As String) As Boolean

        Try
            Dim MasterRows() As DataRow = MasterDS.Tables(0).Select("BoNum='" & BoNum & "'")
            'Dim DetailRows() As DataRow = DetailDS.Tables(0).Select("BoNum='" & BoNum & "'")
            Dim sql As String
            If MasterRows.Length > 0 Then
                MasterDS.Tables(0).Rows.Remove(MasterRows(0))
            End If
            MasterDS.AcceptChanges()
            'If DetailRows.Length > 0 Then
            '    DetailDS.Tables(0).Rows.Remove(DetailRows(0))
            'End If
            'DetailDS.AcceptChanges()
            sql = "Delete Stor_TradeMaster where BoNum='" & BoNum & "';"
            sql += " Delete Stor_TradeDetail where BoNum='" & BoNum & "';"
            sql += " Delete Stor_element where BoNumA='" & BoNum & "'"
            ReturnObject(sql)
            Return True
        Catch ex As Exception
            MsgBox("DeleteDataset:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Private Sub BtnActionFind()
        Try
            Dim sql As String
            Dim whereCondition As String = ""

            If Me.BoNum.Text.Length > 0 Then
                whereCondition = " and a.BoNum like '%" & Me.BoNum.Text & "%'"
            End If

            If Me.PoNum.Text.Length > 0 Then
                whereCondition = " and  g.PoNum = '" & Me.PoNum.Text & "' "
            End If

            If Me.cbStartDate1.Checked = True And Me.cbEndDate1.Checked = False Then
                whereCondition += " and Convert(varchar(10),OperateDate,21)='" & Format(Me.StartDate1.Value, "yyyy-MM-dd") & "'"
            ElseIf Me.cbStartDate1.Checked = False And Me.cbEndDate1.Checked = True Then
                whereCondition += " and Convert(varchar(10),OperateDate,21)='" & Format(Me.EndDate1.Value, "yyyy-MM-dd") & "'"
            ElseIf Me.cbStartDate1.Checked = True And Me.cbEndDate1.Checked = True Then
                whereCondition += " and Convert(varchar(10),OperateDate,21) between '" & Format(Me.StartDate1.Value, "yyyy-MM-dd") & "' and '" & Format(Me.EndDate1.Value, "yyyy-MM-dd") & "'"
            End If

            If Me.cbStartDate2.Checked = True And Me.CheckBox5.Checked = False Then
                whereCondition += " and Convert(varchar(10),h.Date,21)='" & Format(Me.StartDate2.Value, "yyyy-MM-dd") & "'"
            ElseIf Me.cbStartDate2.Checked = False And Me.CheckBox5.Checked = True Then
                whereCondition += " and Convert(varchar(10),h.Date,21)='" & Format(Me.cbEndDate2.Value, "yyyy-MM-dd") & "'"
            ElseIf Me.cbStartDate2.Checked = True And Me.CheckBox5.Checked = True Then
                whereCondition += " and Convert(varchar(10),h.Date,21) between '" & Format(Me.StartDate2.Value, "yyyy-MM-dd") & "' and '" & Format(Me.cbEndDate2.Value, "yyyy-MM-dd") & "'"
            End If

            If Me.DeliverNo.Text.Length > 0 Then
                whereCondition += " and DeliverNo='" & Me.DeliverNo.Text & "'"
            End If

            If Me.cbStartDate3.Checked = True And Me.cbEndDate3.Checked = False Then
                whereCondition += " and DeliverDate='" & Format(Me.StartDate3.Value, "yyyy-MM-dd") & "'"
            ElseIf Me.cbStartDate3.Checked = False And Me.cbEndDate3.Checked = True Then
                whereCondition += " and DeliverDate='" & Format(Me.EndDate3.Value, "yyyy-MM-dd") & "'"
            ElseIf Me.cbEndDate3.Checked = True And Me.cbEndDate3.Checked = True Then
                whereCondition += " and DeliverDate between '" & Format(Me.StartDate3.Value, "yyyy-MM-dd") & "' and '" & Format(Me.EndDate3.Value, "yyyy-MM-dd") & "'"
            End If

            If Me.txtfBatch.Text.Length > 0 Then
                whereCondition += " and Batch='" & Me.txtfBatch.Text & "'"
            End If

            If Me.txtStorePlace.Text.Length > 0 Then
                whereCondition += " and OperatePerson='" & Me.txtStorePlace.SelectedValue.ToString & "'"
            End If

            If Me.txtStore.Text.Length > 0 Then
                whereCondition += " and a.ToStore='" & Me.txtStore.SelectedValue.ToString & "'"
            End If

            If Me.txtStoreType.Text.Length > 0 Then
                whereCondition += " and a.InOrOutType='" & Me.txtStoreType.SelectedValue.ToString & "'"
            End If

            If Me.txtBoStatus.Text.Length > 0 Then
                whereCondition += " and BoStatus='" & Me.txtBoStatus.SelectedValue.ToString & "'"
            End If

            sql = "select Distinct(a.BoNum),b.TradeType,c.InOrOutType,d.ToStore,e.FromStore,a.StorePlace,a.DeliverNo,a.DeliverPerson,a.DeliverDate,a.DeliverCar,a.Batch,BoStatus=f.ListA,"
            sql += "a.Remark,a.OperatePerson,a.OperateDate,a.CheckPerson,a.CheckDate,'' as PoNum,h.Date  from Stor_TradeMaster a left join "
            sql += " (select a.BoNum,b.name as TradeType from Stor_TradeMaster a inner join Stor_tradecode b on a.TradeType=b.AddorNot where b.code='01') b on a.BoNum=b.BoNum left join "
            sql += " (select a.BoNum,b.ListA as InOrOutType from Stor_TradeMaster a inner join BSC_OtherDefineB b on a.InOrOutType=b.ListCode where b.ItemNo=57) c on a.BoNum=c.BoNum left join "
            sql += " (select a.BoNum,b.fShortName as ToStore from Stor_TradeMaster a inner join BSC_StoreHouse b on a.ToStore=b.fCode) d on a.BoNum=d.boNum left join  "
            sql += " (select a.BoNum,b.fShortName as FromStore from Stor_TradeMaster a inner join BSC_StoreHouse b on a.FromStore=b.fCode) e on a.BoNum=e.BoNum left join BSC_OtherDefineB f on a.BoStatus=f.ListCode  "
            sql += "left join Stor_TradeDetail g on a.BoNum = g.BoNum left join Pur_POA h on g.Ponum = h.Num"
            sql += " where f.ItemNo=16 and a.TradeType='+'" & whereCondition

            MasterDS = ReturnDataset(sql)
            Me.DGV_Master.DataSource = MasterDS.Tables(0)
            bFind = MasterDS.Tables(0).Rows.Count > 0
            '' SetGridRowBackColor(Me.DGV_Master, MasterDS)
            GetToolEnable()
        Catch ex As Exception
            MsgBox("BtnActionFind:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub SetGridRowBackColor(ByVal Grid As DataGridView, ByVal DS As DataSet)
        Try
            If DS.Tables(0).Rows.Count <= 0 Then Exit Sub

            For i As Integer = 0 To DS.Tables(0).Rows.Count - 1
                If DS.Tables(0).Rows(i).Item("BoStatus").ToString = "核准" Then
                    Grid.Rows(i).DefaultCellStyle.BackColor = System.Drawing.SystemColors.Info
                ElseIf DS.Tables(0).Rows(i).Item("BoStatus").ToString = "反核准" Then
                    Grid.Rows(i).DefaultCellStyle.BackColor = Color.DeepSkyBlue
                ElseIf DS.Tables(0).Rows(i).Item("BoStatus").ToString = "保存" Then
                    Grid.Rows(i).DefaultCellStyle.BackColor = Color.AliceBlue
                ElseIf DS.Tables(0).Rows(i).Item("BoStatus").ToString = "結案" Then
                    Grid.Rows(i).DefaultCellStyle.BackColor = Color.Gainsboro
                End If
            Next

        Catch ex As Exception
            MsgBox("SetGridRowBackColor:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub FillText(ByVal BoNum As String)
        Try
            Dim sql As String
            Dim Rows() As DataRow = MasterDS.Tables(0).Select("BoNum='" & BoNum & "'")
            If Rows.Length > 0 Then
                Me.LabInfo.Text = Rows(0).Item("BoNum")
                Me.cbInStoreType.Text = Rows(0).Item("InOrOutType")
                Me.cbToStore.Text = Rows(0).Item("ToStore") & ""
                Me.cbFromStore.Text = Rows(0).Item("FromStore") & ""
                Me.cmbStatus.Text = Rows(0).Item("BoStatus") & ""
                Me.txtDeliverNo.Text = Rows(0).Item("DeliverNo") & ""
                If Rows(0).Item("DeliverDate") & "" = "" Then
                Else
                    Me.DateTimePicker1.Value = CDate(Rows(0).Item("DeliverDate") & "")
                End If
                Me.txtDeliverPerson.Text = Rows(0).Item("DeliverPerson") & ""
                Me.txtCarNo.Text = Rows(0).Item("DeliverCar") & ""
                Me.txtRemark.Text = Rows(0).Item("Remark") & ""
            End If
            sql = "select a.ItemNo,a.PoNum,a.PoNumItem,a.GoodsBarCode,a.GoodsCode,a.ENName,a.SupperItem,a.GoodsName,a.GoodsColor,a.GoodsSpec,QTy='',a.Goodsamount,a.Batch as BatchNo,a.StorePlace,GoodsOther,isnull(PackingNum,1)*Goodsamount as PackingNum Into #AA from V_OutStoreDetail a where a.BoNum='" & BoNum & "'"
            sql += "select * from #AA order by ItemNo,PoNumItem;"
            sql += "drop table #AA ;"

            DetailDS = ReturnDataset(sql)
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
            If DetailDS.Tables(0).Rows.Count > 0 Then
                Me.DGV_Sum.Rows(0).Cells("goodsamount").Value = Format(DetailDS.Tables(0).Compute("sum(goodsamount)", ""), "#0.00")
                Me.DGV_Sum.Rows(0).Cells("PackingNum").Value = Format(DetailDS.Tables(0).Compute("sum(PackingNum)", ""), "#0.00")
            Else
                Me.DGV_Sum.Rows(0).Cells("goodsamount").Value = "0.00"
                Me.DGV_Sum.Rows(0).Cells("PackingNum").Value = "0.00"
            End If
            If Me.DGV_Detail.Columns("QTy").Visible = True Then
                Me.DGV_Detail.Columns("QTy").Visible = False
                Me.DGV_Sum.Columns("QTy").Visible = False
            End If
            If DetailDS.Tables(0).Rows.Count > 0 Then
                If DetailDS.Tables(0).Rows(0).Item("PoNum") Is DBNull.Value Or DetailDS.Tables(0).Rows(0).Item("PoNum") & "" = "" Then
                    If Me.DGV_Detail.Columns("PoNum").Visible = True Then
                        Me.DGV_Detail.Columns("PoNum").Visible = False
                        Me.DGV_Sum.Columns("PoNum").Visible = False
                    End If
                    If Me.DGV_Detail.Columns("PoNumItem").Visible = True Then
                        Me.DGV_Detail.Columns("PoNumItem").Visible = False
                        Me.DGV_Sum.Columns("PoNumItem").Visible = False
                    End If
                Else
                    If Me.DGV_Detail.Columns("PoNum").Visible = False Then
                        Me.DGV_Detail.Columns("PoNum").Visible = True
                        Me.DGV_Sum.Columns("PoNum").Visible = True
                    End If
                    If Me.DGV_Detail.Columns("PoNumItem").Visible = False Then
                        Me.DGV_Detail.Columns("PoNumItem").Visible = True
                        Me.DGV_Sum.Columns("PoNumItem").Visible = True
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("FillText:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub FillElement(ByVal BarCode As String)
        Try
            Dim CurrentID As String = Me.DGV_Detail.CurrentRow.Cells(0).Value
            Dim Rows() As DataRow = DetailDS.Tables(0).Select("ItemNo='" & CurrentID & "' and GoodsBarCode='" & BarCode & "'")
            Dim GoodsRows() As DataRow = GoodsDS.Tables(0).Select("BarCode='" & BarCode & "'")
            If Rows.Length > 0 Then
                Me.txtBoNum.Text = ""
                Me.txtbarcode.Text = ""
                Me.txtcode.Text = ""
                Me.txtName.Text = ""
                Me.txtcolor.Text = ""
                Me.txtsize.Text = ""
                Me.txtbatch.Text = ""
                Me.txtplace.Text = ""
                Me.txtGoodsCount.Text = ""
                Me.txtBoNum.Text = Me.LabInfo.Text
                Me.txtbarcode.Text = BarCode
                Me.txtcode.Text = Rows(0).Item("GoodsCode") & ""
                Me.txtName.Text = Rows(0).Item("GoodsName") & ""
                Me.txtcolor.Text = Rows(0).Item("GoodsColor") & ""
                Me.txtsize.Text = Rows(0).Item("GoodsSpec") & ""
                Me.txtbatch.Text = Rows(0).Item("BatchNo") & ""
                Me.txtelementbatch.Text = Rows(0).Item("BatchNo") & ""
                Me.txtplace.Text = Rows(0).Item("StorePlace") & ""
                Me.StorePlace.Text = Rows(0).Item("StorePlace") & ""
                Me.txtGoodsCount.Text = Rows(0).Item("Goodsamount") & ""
                Me.txtelementtimes.Text = Rows(0).Item("Goodsamount") & ""
            End If

            Dim sql As String
            Dim ElementDS As New DataSet

            sql = "select Element,Elementamount,ElementUnit,Elementbatch,StorePlace,ElementStatus from Stor_element where BoNumA='" & Me.LabInfo.Text & "' and GoodsBarCode='*" & BarCode & "*' " '' and elementbatch='" + txtbatch.Text + "'"
            Try
                ElementDS = ReturnDataset(sql)
                Me.dgv_Element.DataSource = ElementDS.Tables(0)
            Catch ex As Exception
            Finally
                ElementDS = Nothing
            End Try


        Catch ex As Exception
            MsgBox("FillElement:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Function IsAmountClose() As Boolean

        Try

            Dim sql As String = ""
            Dim m_Ds As New DataSet
            IsClose = True
            sql = "select * from BSC_SystemProfile where FKey like '%" & PubCompanyCode & "%'"
            m_Ds = ReturnDataset(sql)
            If m_Ds.Tables(0).Rows.Count > 0 Then
                PeriodData = m_Ds.Tables(0).Rows(0).Item("FValue")
                IsClose = CType(m_Ds.Tables(0).Rows(1).Item("FValue"), Boolean)
            End If
            Return IsClose
        Catch ex As Exception
            MsgBox("IsAmountClose" & ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Private Sub SetToolEnable()

        Dim ShopNo As String = ""
        Dim DeliverDate As String = ""
        If Me.DGV_Master.Rows.Count > 0 Then
            ShopNo = Me.DGV_Master.CurrentRow.Cells("ToStore").Value
            If Me.DGV_Master.CurrentRow.Cells("DeliverDate").Value & "" <> "" Then
                DeliverDate = Me.DGV_Master.CurrentRow.Cells("DeliverDate").Value.ToString.Replace("-", "").Substring(0, 6)
            End If


            Select Case Me.DGV_Master.CurrentRow.Cells("BoStatus").Value
                Case "保存"
                    MainForm.ToolStripPrint.Enabled = True
                    If ShopNo = PubCompanyName Then
                        MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True
                        MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                    Else
                        MainForm.ToolStripCheck.Enabled = False
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    End If
                Case "核准"
                    If ShopNo = PubCompanyName Then
                        MainForm.ToolStripPrint.Enabled = True
                        MainForm.ToolStripCheck.Enabled = False
                        If DeliverDate < PeriodData Then
                            MainForm.ToolStripUnCheck.Enabled = False
                        Else
                            MainForm.ToolStripUnCheck.Enabled = True And UncheckEnable = True
                        End If
                        MainForm.ToolStripComplete.Enabled = True And CompleteEnable = True
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    Else
                        MainForm.ToolStripPrint.Enabled = True
                        MainForm.ToolStripCheck.Enabled = False
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    End If
                Case "反核准"
                    MainForm.ToolStripPrint.Enabled = True
                    If ShopNo = PubCompanyName Then
                        MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True And UncheckEnable = True
                        MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                    Else
                        MainForm.ToolStripCheck.Enabled = False
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                    End If
                Case "結案"
                    MainForm.ToolStripPrint.Enabled = True
                    MainForm.ToolStripCheck.Enabled = False
                    MainForm.ToolStripUnCheck.Enabled = False
                    MainForm.ToolStripComplete.Enabled = False
                    MainForm.ToolStripDelete.Enabled = False
                    MainForm.ToolStripEdit.Enabled = False
            End Select
        End If

    End Sub

    Private Sub GetToolEnable()
        Try
            With MainForm
                .ToolStripAdd.Enabled = AddEnable
                .ToolStripEdit.Enabled = EditEnable And bFind = True
                .ToolStripDelete.Enabled = DeleteEnable And bFind = True
                .ToolStripPrint.Enabled = PrintEnable
                .ToolStripImport.Enabled = ImportEnable
                .ToolStripExport.Enabled = ExportEnable
                .ToolStripFind.Enabled = FindEnable
                .ToolStripFilter.Enabled = True
                .ToolStripCheck.Enabled = CheckEnable
                .ToolStripUnCheck.Enabled = UncheckEnable
                .ToolStripComplete.Enabled = CompleteEnable
                .AddToolStripMenuItem.Enabled = .ToolStripAdd.Enabled
                .Edit1ToolStripMenuItem.Enabled = .ToolStripEdit.Enabled
                .DelToolStripMenuItem.Enabled = .ToolStripDelete.Enabled
                .SaveToolStripMenuItem.Enabled = .ToolStripSave.Enabled
                .CancelToolStripMenuItem.Enabled = .ToolStripCancel.Enabled
                .PrintToolStripMenuItem.Enabled = .ToolStripPrint.Enabled
                .ExportToolStripMenuItem.Enabled = .ToolStripImport.Enabled
                .ImportToolStripMenuItem.Enabled = .ToolStripExport.Enabled
                .FilterToolStripMenuItem.Enabled = .ToolStripFilter.Enabled
            End With

        Catch ex As Exception
            MsgBox("GetToolEnable:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub AddDataToGrid(ByVal BarCode As String, Optional ByVal qty As Int32 = -100)

        Try
            Dim Str() As String = BarCode.Split("^")
            Dim Rows() As DataRow
            For i As Integer = 0 To Str.Length - 1
                Rows = GoodsDS.Tables(0).Select("BarCode='" & Str(i) & "'")
                If Rows.Length > 0 Then
                    Dim NewRow As DataRow = DetailDS.Tables(0).NewRow
                    NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                    NewRow("GoodsBarCode") = Rows(0).Item("BarCode") & ""
                    NewRow("GoodsCode") = Rows(0).Item("Code") & ""
                    NewRow("ENName") = Rows(0).Item("enname") & ""
                    NewRow("SupperItem") = Rows(0).Item("SupperItem") & ""
                    NewRow("GoodsName") = Rows(0).Item("Cnname") & ""
                    NewRow("GoodsColor") = Rows(0).Item("Color") & ""
                    NewRow("GoodsSpec") = Rows(0).Item("Spec") & ""
                    If qty <> -100 Then
                        NewRow("Goodsamount") = qty
                    End If
                    DetailDS.Tables(0).Rows.Add(NewRow)
                End If
            Next

            If Str.Length > 0 Then

                DetailDS.AcceptChanges()
                Me.DGV_Detail.DataSource = DetailDS.Tables(0)

                For i As Int16 = 0 To Me.DGV_Detail.Rows.Count - 2
                    If Me.DGV_Detail.Rows(i).IsNewRow = False Then
                        If Me.DGV_Detail.Rows(i).Cells("GoodsBarCode").Value Is DBNull.Value Then
                            Me.DGV_Detail.Rows.RemoveAt(i)
                        End If
                    End If
                Next
                Me.DGV_Detail.Focus()
                If Me.DGV_Detail.Rows.Count > 1 Then
                    If Me.DGV_Detail.Rows.Count = 2 Then
                        Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("Goodsamount")
                    Else
                        Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index + 1).Cells("Goodsamount")
                    End If
                End If
            End If

        Catch ex As Exception
            MsgBox("AddDataToGrid:" & ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub


    Private Sub AddDataToGrid1(ByVal BarCode As String, Optional ByVal qty As Int32 = -100)

        Try
            Dim Str() As String = BarCode.Split("^")
            Dim Rows() As DataRow
            For i As Integer = 0 To Str.Length - 1
                Rows = GoodsDS.Tables(0).Select("BarCode='" & Str(i) & "'")
                If Rows.Length > 0 Then
                    Dim PackingNum As Integer
                    PackingNum = CType(Rows(0).Item("PackingNum"), Integer)
                    If PackingNum > 1 Then '包裝數量大於1的時候
                        For J As Integer = 0 To PackingNum - 1
                            Dim Num As String
                            Dim NewRow As DataRow = DetailDS.Tables(0).NewRow

                            Num = Format(J + 1, "000")
                            NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                            NewRow("GoodsBarCode") = Rows(0).Item("BarCode") & "-" & Num
                            NewRow("GoodsCode") = Rows(0).Item("Code") & ""
                            NewRow("ENName") = Rows(0).Item("enname") & ""
                            NewRow("SupperItem") = Rows(0).Item("SupperItem") & ""
                            NewRow("GoodsName") = Rows(0).Item("Cnname") & ""
                            NewRow("GoodsColor") = Rows(0).Item("Color") & ""
                            NewRow("GoodsSpec") = Rows(0).Item("Spec") & ""
                            If qty <> -100 Then
                                NewRow("Goodsamount") = qty
                            End If
                            DetailDS.Tables(0).Rows.Add(NewRow)
                            DetailDS.Tables(0).AcceptChanges()

                        Next
                    Else

                        Dim NewRow As DataRow = DetailDS.Tables(0).NewRow
                        NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                        NewRow("GoodsBarCode") = Rows(0).Item("BarCode") & ""
                        NewRow("GoodsCode") = Rows(0).Item("Code") & ""
                        NewRow("ENName") = Rows(0).Item("enname") & ""
                        NewRow("SupperItem") = Rows(0).Item("SupperItem") & ""
                        NewRow("GoodsName") = Rows(0).Item("Cnname") & ""
                        NewRow("GoodsColor") = Rows(0).Item("Color") & ""
                        NewRow("GoodsSpec") = Rows(0).Item("Spec") & ""
                        If qty <> -100 Then
                            NewRow("Goodsamount") = qty
                        End If
                        DetailDS.Tables(0).Rows.Add(NewRow)
                        DetailDS.Tables(0).AcceptChanges()

                    End If

                End If
            Next

            If Str.Length > 0 Then

                DetailDS.AcceptChanges()
                Me.DGV_Detail.DataSource = DetailDS.Tables(0)

                For i As Int16 = 0 To Me.DGV_Detail.Rows.Count - 2
                    If Me.DGV_Detail.Rows(i).IsNewRow = False Then
                        If Me.DGV_Detail.Rows(i).Cells("GoodsBarCode").Value Is DBNull.Value Then
                            Me.DGV_Detail.Rows.RemoveAt(i)
                        End If
                    End If
                Next
                Me.DGV_Detail.Focus()
                If Me.DGV_Detail.Rows.Count > 1 Then
                    If Me.DGV_Detail.Rows.Count = 2 Then
                        Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("Goodsamount")
                    Else
                        Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index + 1).Cells("Goodsamount")
                    End If
                End If
            End If

        Catch ex As Exception
            MsgBox("AddDataToGrid:" & ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

#End Region


#Region "Control Events"


    Private Sub ComBo_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComBo.SelectedValueChanged
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Me.DGV_Detail.CurrentCell.Value = Me.ComBo.SelectedValue.ToString
                Dim Rows() As DataRow = GoodsDS.Tables(0).Select("BarCode='" & Me.ComBo.SelectedValue.ToString & "'")
                If Rows.Length > 0 Then
                    Me.DGV_Detail.CurrentRow.Cells("GoodsCode").Value = Rows(0).Item("Code")
                    Me.DGV_Detail.CurrentRow.Cells("GoodsName").Value = Rows(0).Item("ShortName")
                    Me.DGV_Detail.CurrentRow.Cells("GoodsColor").Value = Rows(0).Item("Color")
                    Me.DGV_Detail.CurrentRow.Cells("GoodsSpec").Value = Rows(0).Item("Spec")
                End If
            End If
        Catch ex As Exception
            MsgBox("ComBo_SelectedValueChanged:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub DGV_Detail_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Detail.CellDoubleClick

        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If e.ColumnIndex = 4 Then
                    If Me.cbInStoreType.SelectedIndex = 7 Then
                        Exit Sub
                    End If
                    Dim Frm_SelectGoods As New Frm_SelectGoods
                    Frm_SelectGoods.ShowDialog()
                    If Frm_SelectGoods.BarCode Is Nothing Then
                        Exit Sub
                    End If
                    Dim BarCode As String = Frm_SelectGoods.BarCode
                    If BarCode.Length <= 0 Then Exit Sub
                    If Me.cbInStoreType.SelectedIndex = 10 Then
                        AddDataToGrid1(BarCode)
                    Else
                        AddDataToGrid(BarCode)
                    End If



                ElseIf e.ColumnIndex = 13 Then
                    If IsPlace = True Then
                        If Me.Panel2.Visible = False Then
                            Me.Panel2.Visible = True
                            Me.TreeView1.Focus()
                            Me.TreeView1.SelectedNode = SelectNode
                            Dim rect As Rectangle = Me.DGV_Detail.GetCellDisplayRectangle(Me.DGV_Detail.CurrentCell.ColumnIndex, Me.DGV_Detail.CurrentCell.RowIndex, False)
                            Me.Panel2.Left = rect.Left
                            Me.Panel2.Top = rect.Top + Me.DGV_Detail.CurrentRow.Height
                        Else
                            Me.Panel2.Visible = False
                        End If
                    End If
                End If
            End If

        Catch ex As Exception
            MsgBox("DGV_Detail_CellDoubleClick:" & ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub DGV_Detail_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Detail.CellValueChanged

        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If e.ColumnIndex = 13 Then
                    Me.DGV_Detail.Update()
                    Dim sql As String
                    Dim m_Ds As New DataSet
                    Dim Arrary As New ArrayList
                    Dim DatafVirtual As String = ""
                    Dim fBuJian As String = ""
                    Dim fIsTemp As Boolean
                    Dim CurrentStorePlace As String = ""
                    Dim CurrentBarCode As String = ""
                    Dim CurrentBatch As String = ""
                    Dim RowBarcode As String = ""
                    Dim RowBatch As String = ""
                    Dim RowStoreplace As String = ""
                    Dim RowIndex As Integer = 0
                    Dim RowSum As Double = 0
                    If Not Me.DGV_Detail.CurrentRow.Cells("StorePlace").Value Is DBNull.Value Then
                        CurrentStorePlace = Me.DGV_Detail.CurrentRow.Cells("StorePlace").Value
                    End If
                    If Not Me.DGV_Detail.CurrentRow.Cells("GoodsBarcode").Value Is DBNull.Value Then
                        CurrentBarCode = Me.DGV_Detail.CurrentRow.Cells("GoodsBarcode").Value
                    End If
                    If Not Me.DGV_Detail.CurrentRow.Cells("BatchNo").Value Is DBNull.Value Then
                        CurrentBatch = Me.DGV_Detail.CurrentRow.Cells("BatchNo").Value
                    End If

                    Dim StoreRow() As DataRow = StoreageDS.Tables(0).Select("fStorageId='" & CurrentStorePlace & "'")
                    If StoreRow.Length > 0 Then
                        DatafVirtual = StoreRow(0).Item("fVirtual") & ""
                        fBuJian = StoreRow(0).Item("fBuJian") & ""
                        fIsTemp = CType(StoreRow(0).Item("fIsTemp"), Boolean)
                        If DatafVirtual = "1" Then
                            MsgBox("該倉位是壞貨倉位，不能將貨品放在此倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                            Me.DGV_Detail.CurrentRow.Cells("StorePlace").Value = ""
                            Me.DGV_Detail.Focus()
                            Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("StorePlace")
                            Exit Sub
                        Else
                            If fIsTemp = False Then
                                sql = "select a.*,b.fVirtual,b.fBuJian from "
                                sql += "(select Period,StoreHouse,Replace(BarCode,'*','') as BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_Storequery where StoreHouse='" & PubCompanyCode & "' and StorePlace='" & CurrentStorePlace & "' group by StoreHouse,Period,barcode,Batch,StorePlace) a "
                                sql += "left join BSC_Storage b on a.Storeplace=b.fStorageId  where isnull(a.Goodsamount,0.00)>0"
                                m_Ds = ReturnDataset(sql)

                                If m_Ds.Tables(0).Rows.Count > 0 Then
                                    Dim BarCode As String = m_Ds.Tables(0).Rows(0).Item("BarCode") & ""
                                    Dim Batch As String = m_Ds.Tables(0).Rows(0).Item("Batch") & ""
                                    Dim Goodsamount As Double = Convert.ToDouble(m_Ds.Tables(0).Rows(0).Item("Goodsamount"))

                                    If fBuJian = "1" Then
                                        If String.Compare(CurrentBarCode, BarCode) <> 0 Then
                                            MsgBox("同一倉位下不能存放兩種貨品，請選擇其他倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                            Me.DGV_Detail.Focus()
                                            Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("StorePlace")
                                        End If
                                    Else
                                        If String.Compare(CurrentBarCode, BarCode) = 0 Then
                                            If String.Compare(CurrentBatch, Batch) = 0 Then
                                            Else
                                                MsgBox("同一倉位下不能存放兩個批次，請選擇其他倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                                Me.DGV_Detail.Focus()
                                                Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("StorePlace")
                                            End If
                                        Else
                                            MsgBox("同一倉位下不能存放兩種貨品，請選擇其他倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                            Me.DGV_Detail.Focus()
                                            Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("StorePlace")
                                        End If
                                    End If
                                End If

                                Dim Rows() As DataRow = DetailDS.Tables(0).Select("GoodsBarcode<>'" & CurrentBarCode & "' and StorePlace='" & CurrentStorePlace & "'")
                                If fBuJian = "1" Then
                                    If Rows.Length > 0 Then
                                        MsgBox("同一倉位下不能存放兩種貨品，請選擇其他倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.DGV_Detail.Focus()
                                        Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("StorePlace")
                                    End If
                                Else
                                    If Rows.Length > 0 Then
                                        MsgBox("同一倉位下不能存放兩種貨品，請選擇其他倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.DGV_Detail.Focus()
                                        Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("StorePlace")
                                    Else
                                        Dim DrRows() As DataRow = DetailDS.Tables(0).Select("GoodsBarcode='" & CurrentBarCode & "' and BatchNo<>'" & CurrentBatch & "' and StorePlace='" & CurrentStorePlace & "'")
                                        If DrRows.Length > 0 Then
                                            MsgBox("同一倉位下不能存放兩個批次，請選擇其他倉位！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                            Me.DGV_Detail.Focus()
                                            Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("StorePlace")
                                        End If
                                    End If
                                End If

                                For i As Integer = 0 To Me.DGV_Detail.Rows.Count - 1
                                    If Not Me.DGV_Detail.Rows(i).IsNewRow Then
                                        If Not Me.DGV_Detail.Rows(i).Cells("GoodsBarCode").Value Is DBNull.Value Then
                                            RowBarcode = Me.DGV_Detail.Rows(i).Cells("GoodsBarCode").Value
                                        End If

                                        If Not Me.DGV_Detail.Rows(i).Cells("BatchNo").Value Is DBNull.Value Then
                                            RowBatch = Me.DGV_Detail.Rows(i).Cells("BatchNo").Value
                                        End If


                                        If Not Me.DGV_Detail.Rows(i).Cells("StorePlace").Value Is DBNull.Value Then
                                            RowStoreplace = Me.DGV_Detail.Rows(i).Cells("StorePlace").Value
                                        End If

                                        If RowBarcode.ToLower = CurrentBarCode.ToLower And RowBatch.ToLower = CurrentBatch.ToLower And RowStoreplace.ToLower = CurrentStorePlace.ToLower Then
                                            RowIndex += 1
                                            Arrary.Add(i)
                                        End If
                                    End If
                                Next
                                If RowIndex > 1 Then
                                    MsgBox("列表中存在相同的記錄，數量列將合並！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                    For j As Integer = 0 To Arrary.Count - 1
                                        RowSum += Convert.ToDouble(Me.DGV_Detail.Rows(Arrary(j)).Cells("Goodsamount").Value)
                                    Next
                                    For i As Integer = 1 To Arrary.Count - 1
                                        Me.DGV_Detail.Rows.RemoveAt(Arrary(i))
                                    Next
                                    For i As Integer = 0 To DetailDS.Tables(0).Rows.Count - 2
                                        DetailDS.Tables(0).Rows(i).Item("ItemNo") = Format(i + 1, "000")
                                    Next
                                    DetailDS.AcceptChanges()
                                    Me.DGV_Detail.DataSource = DetailDS.Tables(0)
                                    Me.DGV_Detail.Focus()
                                    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Arrary(0)).Cells("Goodsamount")
                                    Me.DGV_Detail.Rows(Arrary(0)).Cells("Goodsamount").Value = RowSum
                                End If
                                Me.DGV_Detail.CurrentRow.Cells("StorePlace").Value = Me.DGV_Detail.CurrentRow.Cells("StorePlace").Value.ToString.ToUpper
                            End If
                        End If
                    Else
                        MsgBox("對不起，該倉位不存在！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Me.DGV_Detail.Focus()
                        Me.DGV_Detail.CurrentCell = Me.DGV_Detail.CurrentRow.Cells("StorePlace")
                    End If
                ElseIf e.ColumnIndex = 10 Then
                    Me.DGV_Sum.Rows(0).Cells("Goodsamount").Value = Format(DetailDS.Tables(0).Compute("sum(Goodsamount)", ""), "#0.00")
                End If
            End If
        Catch ex As Exception
            MsgBox("DGV_Detail_CellValueChanged:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DGV_Detail_ColumnWidthChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles DGV_Detail.ColumnWidthChanged
        SetGridWidth()
    End Sub

    Private Sub DGV_Detail_Scroll(ByVal sender As Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles DGV_Detail.Scroll
        If Me.Panel2.Visible = True Then
            Me.Panel2.Visible = False
        End If
        'Me.DGV_Sum.FirstDisplayedScrollingColumnIndex = Me.DGV_Detail.FirstDisplayedScrollingColumnIndex
        Me.DGV_Sum.HorizontalScrollingOffset = Me.DGV_Detail.HorizontalScrollingOffset
    End Sub

    Private Sub DGV_Detail_CellValidated(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Detail.CellValidated
        Me.LabError.Text = ""
        Me.LabError.Visible = False
        Me.DGV_Detail.Rows(e.RowIndex).ErrorText = Nothing
    End Sub

    Private Sub DGV_Detail_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DGV_Detail.CellValidating
        Try
            Me.LabError.Visible = True
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If e.ColumnIndex = 10 Then
                    Dim testInteger As Double
                    If Me.DGV_Detail.CurrentRow.IsNewRow Then
                        Exit Sub
                    End If
                    If Not e.FormattedValue.ToString.Length = 0 Then
                        If Not Double.TryParse(e.FormattedValue.ToString, testInteger) Then
                            Me.LabError.Text = "無效的輸入!"
                            e.Cancel = True
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("DGV_Master_CellValidating:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DGV_Detail_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_Detail.DoubleClick
        If Me.TabControl1.SelectedIndex <> 2 Then
            Me.TabControl1.SelectedIndex = 2
        End If
    End Sub

    Private Sub DGV_Detail_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGV_Detail.RowPostPaint

        Try
            e.Graphics.DrawString(e.RowIndex + 1, DGV_Detail.DefaultCellStyle.Font, Brushes.Black, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4)
        Catch ex As Exception
            MsgBox("DGV_Detail_RowPostPaint:", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DGV_Detail_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DGV_Detail.KeyDown
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Select Case e.KeyCode
                    Case Keys.Delete
                        Dim CurrentID As String = ""
                        If Me.DGV_Detail.CurrentRow.Cells("ItemNo").Value Is System.DBNull.Value Then
                            Me.DGV_Detail.Rows.RemoveAt(Me.DGV_Detail.CurrentRow.Index)
                        Else
                            CurrentID = Me.DGV_Detail.CurrentRow.Cells("ItemNo").Value
                        End If
                        If CurrentID.Length > 0 Then
                            Dim Rows() As DataRow = DetailDS.Tables(0).Select("ItemNo='" & CurrentID & "'")
                            If MsgBox(My.Resources.ConfirmDelete, MsgBoxStyle.Question + MsgBoxStyle.OkCancel, Msg.CompanyName) = MsgBoxResult.Ok Then
                                DetailDS.Tables(0).Rows.Remove(Rows(0))
                            End If
                            DetailDS.AcceptChanges()
                            For i As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                                DetailDS.Tables(0).Rows(i).Item("ItemNo") = Format(i + 1, "000")
                            Next
                            DetailDS.AcceptChanges()
                            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
                            If DetailDS.Tables(0).Rows.Count > 0 Then
                                Me.DGV_Sum.Rows(0).Cells("goodsamount").Value = Format(DetailDS.Tables(0).Compute("sum(goodsamount)", ""), "#0.00")
                            End If
                        End If
                    Case Keys.D1
                        If e.Control = True Then
                            If Me.DGV_Detail.CurrentCell.ColumnIndex = 4 Then
                                Dim Frm_SelectGoods As New Frm_SelectGoods
                                Frm_SelectGoods.ShowDialog()
                                If Frm_SelectGoods.BarCode Is Nothing Then
                                    Exit Sub
                                End If
                                Dim BarCode As String = Frm_SelectGoods.BarCode
                                If BarCode.Length <= 0 Then Exit Sub
                                AddDataToGrid(BarCode)
                            ElseIf Me.DGV_Detail.CurrentCell.ColumnIndex = 13 Then
                                If IsPlace = True Then
                                    If Me.Panel2.Visible = False Then
                                        Me.Panel2.Visible = True
                                        Me.TreeView1.Focus()
                                        Me.TreeView1.SelectedNode = SelectNode
                                        Dim rect As Rectangle = Me.DGV_Detail.GetCellDisplayRectangle(Me.DGV_Detail.CurrentCell.ColumnIndex, Me.DGV_Detail.CurrentCell.RowIndex, False)
                                        Me.Panel2.Left = rect.Left
                                        Me.Panel2.Top = rect.Top + Me.DGV_Detail.CurrentRow.Height
                                    Else
                                        Me.Panel2.Visible = False
                                    End If
                                End If
                            End If
                        End If
                End Select
            Else
                If e.Control AndAlso e.KeyCode = Keys.C Then
                    Clipboard.SetText(Me.DGV_Detail.SelectedCells(0).Value)
                End If
            End If
        Catch ex As Exception
            MsgBox("DGV_Detail_KeyDown:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub BtnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnFind.Click
        Try
            BtnActionFind()
            SetToolEnable()
        Catch ex As Exception
            MsgBox("BtnFind_Click:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub DGV_Master_Sorted(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_Master.Sorted
        If MasterDS.Tables(0).Rows.Count > 0 Then
            SetGridRowBackColor(Me.DGV_Master, MasterDS)
        End If
    End Sub

    Private Sub DGV_Master_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Master.CellClick
        Try
            SetToolEnable()
        Catch ex As Exception
            MsgBox("DGV_Master_DoubleClick:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub DGV_Master_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_Master.DoubleClick
        Try
            If Me.TabControl1.SelectedIndex <> 1 Then
                Me.TabControl1.SelectedIndex = 1
            End If
        Catch ex As Exception
            MsgBox("DGV_Master_DoubleClick:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub DGV_Master_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGV_Master.RowPostPaint
        Try
            e.Graphics.DrawString(e.RowIndex + 1, DGV_Master.DefaultCellStyle.Font, Brushes.Black, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4)
        Catch ex As Exception
            MsgBox("DGV_Detail_RowPostPaint:", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub TabControl1_Selected(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles TabControl1.Selected
        Try
            If Not Me.TabControl1.SelectedTab Is Nothing Then
                Select Case Me.TabControl1.SelectedIndex
                    Case 0
                        IsFilter = True
                        IsExport = True
                        MainForm.ToolStripImport.Enabled = False
                        MainForm.ToolStripFilter.Enabled = True
                    Case 1
                        If MasterDS.Tables(0).Rows.Count <= 0 Then
                        Else
                            Dim BoNum As String = Me.DGV_Master.CurrentRow.Cells("BoNum").Value
                            FillText(BoNum)
                        End If
                        MainForm.ToolStripFilter.Enabled = False
                    Case 2
                        If DetailDS.Tables(0).Rows.Count <= 0 Then
                        Else
                            Dim Barcode As String = Me.DGV_Detail.CurrentRow.Cells("GoodsBarCode").Value
                            FillElement(Barcode)
                        End If
                End Select
            End If
            SetCtlEnable(False)
        Catch ex As Exception
            MsgBox("TabControl1_Selected:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub TabControl1_Selecting(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles TabControl1.Selecting
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                e.Cancel = True
            End If
        Catch ex As Exception
            MsgBox("TabControl1_Selecting:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub cbInStoreType_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbInStoreType.SelectedIndexChanged
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
            Dim mBool As Boolean
            If Me.cbInStoreType.SelectedIndex = 1 Then
                Me.txtPoNo.Enabled = True
                Me.txtdiaobo.Enabled = False
                Me.txtBackNo.Enabled = False
                Me.txtSaleOrdeNo.Enabled = False
                Me.txtdiaobo.Text = ""
                Me.txtBackNo.Text = ""
                Me.txtSaleOrdeNo.Text = ""
                Me.DGV_Detail.Columns("PoNum").Visible = True
                Me.DGV_Detail.Columns("PoNumItem").Visible = True
                Me.DGV_Detail.Columns("QTy").Visible = True
                Me.DGV_Sum.Columns("PoNum").Visible = True
                Me.DGV_Sum.Columns("PoNumItem").Visible = True
                Me.DGV_Sum.Columns("QTy").Visible = True
                MainForm.ToolStripImport.Enabled = True
                mBool = False
            ElseIf Me.cbInStoreType.SelectedIndex = 2 Then
                Me.txtdiaobo.Enabled = False
                Me.txtPoNo.Enabled = False
                Me.txtSaleOrdeNo.Enabled = False
                Me.txtBackNo.Enabled = True
                Me.txtdiaobo.Text = ""
                Me.txtPoNo.Text = ""
                Me.txtSaleOrdeNo.Text = ""
                If Me.DGV_Detail.Columns("PoNum").Visible = False Then
                    Me.DGV_Detail.Columns("PoNum").Visible = True
                End If
                If Me.DGV_Detail.Columns("PoNumItem").Visible = False Then
                    Me.DGV_Detail.Columns("PoNumItem").Visible = True
                End If
                If Me.DGV_Detail.Columns("QTy").Visible = True Then
                    Me.DGV_Detail.Columns("QTy").Visible = False
                End If
                If Me.DGV_Sum.Columns("PoNum").Visible = True Then
                    Me.DGV_Sum.Columns("PoNum").Visible = False
                End If
                If Me.DGV_Sum.Columns("PoNumItem").Visible = True Then
                    Me.DGV_Sum.Columns("PoNumItem").Visible = False
                End If
                If Me.DGV_Sum.Columns("QTy").Visible = True Then
                    Me.DGV_Sum.Columns("QTy").Visible = False
                End If
                MainForm.ToolStripImport.Enabled = True
                Me.cbFromStore.Enabled = False
                mBool = False
            ElseIf Me.cbInStoreType.SelectedIndex = 3 Then
                Me.txtdiaobo.Enabled = True
                Me.txtPoNo.Enabled = False
                Me.txtBackNo.Enabled = False
                Me.txtSaleOrdeNo.Enabled = False
                Me.txtPoNo.Text = ""
                Me.txtBackNo.Text = ""
                Me.txtSaleOrdeNo.Text = ""
                If Me.DGV_Detail.Columns("PoNum").Visible = False Then
                    Me.DGV_Detail.Columns("PoNum").Visible = True
                End If
                If Me.DGV_Detail.Columns("PoNumItem").Visible = False Then
                    Me.DGV_Detail.Columns("PoNumItem").Visible = True
                End If
                If Me.DGV_Detail.Columns("QTy").Visible = True Then
                    Me.DGV_Detail.Columns("QTy").Visible = False
                Else

                End If
                If Me.DGV_Detail.Columns("QTy").Visible = True Then
                    Me.DGV_Detail.Columns("QTy").Visible = False
                End If
                If Me.DGV_Sum.Columns("PoNumItem").Visible = True Then
                    Me.DGV_Sum.Columns("PoNumItem").Visible = False
                End If
                If Me.DGV_Sum.Columns("QTy").Visible = True Then
                    Me.DGV_Sum.Columns("QTy").Visible = False
                End If
                MainForm.ToolStripImport.Enabled = True
                Me.cbFromStore.Enabled = False
                mBool = False
            ElseIf Me.cbInStoreType.SelectedIndex = 4 Then
                Me.txtPoNo.Enabled = False
                Me.txtBackNo.Enabled = False
                Me.txtdiaobo.Enabled = False
                txtSaleOrdeNo.Enabled = True
                Me.txtPoNo.Text = ""
                Me.txtBackNo.Text = ""
                Me.txtdiaobo.Text = ""
                If Me.DGV_Detail.Columns("PoNum").Visible = False Then
                    Me.DGV_Detail.Columns("PoNum").Visible = True
                End If
                If Me.DGV_Detail.Columns("PoNumItem").Visible = False Then
                    Me.DGV_Detail.Columns("PoNumItem").Visible = True
                End If
                If Me.DGV_Detail.Columns("QTy").Visible = True Then
                    Me.DGV_Detail.Columns("QTy").Visible = False
                End If
                If Me.DGV_Sum.Columns("PoNum").Visible = False Then
                    Me.DGV_Sum.Columns("PoNum").Visible = True
                End If
                If Me.DGV_Sum.Columns("PoNumItem").Visible = False Then
                    Me.DGV_Sum.Columns("PoNumItem").Visible = True
                End If
                If Me.DGV_Sum.Columns("QTy").Visible = True Then
                    Me.DGV_Sum.Columns("QTy").Visible = False
                End If
                MainForm.ToolStripImport.Enabled = True
                mBool = False
            Else
                mBool = True
                Me.txtPoNo.Enabled = False
                Me.txtdiaobo.Enabled = False
                Me.txtBackNo.Enabled = False
                Me.txtSaleOrdeNo.Enabled = False
                Me.txtdiaobo.Text = ""
                Me.txtPoNo.Text = ""
                Me.txtBackNo.Text = ""
                Me.txtSaleOrdeNo.Text = ""
                Me.DGV_Detail.Columns("PoNum").Visible = False
                Me.DGV_Detail.Columns("PoNumItem").Visible = False
                Me.DGV_Detail.Columns("QTy").Visible = False
                Me.DGV_Sum.Columns("PoNum").Visible = False
                Me.DGV_Sum.Columns("PoNumItem").Visible = False
                Me.DGV_Sum.Columns("QTy").Visible = False
                MainForm.ToolStripImport.Enabled = False
                Me.cbFromStore.Enabled = False
            End If

        End If

    End Sub

    Private Sub txtGoodsBarCode_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub txtGoodsBarCode_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Try



        Catch ex As Exception
            MsgBox("txtGoodsBarCode_TextChanged:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub txtPoNo_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPoNo.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then
                If Me.txtPoNo.Text.Length <= 0 Then Exit Sub
                Dim sql As String = ""

                sql = "select ItemNo='',* into #BB from V_GetCheckedPoNum where PoNum='" & Me.txtPoNo.Text.Trim & "';"
                sql += "select * from #BB where isnull(Goodsamount,0.00)>0 order by PoNumItem;"
                sql += "drop table #BB;"
                DetailDS = ReturnDataset(sql)
                If DetailDS.Tables(0).Rows.Count <= 0 Then
                    MsgBox("該采購單已入庫或不存在，不能重複操作！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Else
                    For i As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                        DetailDS.Tables(0).Rows(i).Item("ItemNo") = Format(i + 1, "000")
                    Next
                    DetailDS.AcceptChanges()
                    Me.DGV_Detail.DataSource = DetailDS.Tables(0)
                End If
            End If

        Catch ex As Exception
            MsgBox("txtPoNo_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub txtdiaobo_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtdiaobo.KeyDown

        Try
            If e.KeyCode = Keys.Enter Then
                If Me.txtdiaobo.Text.Length <= 0 Then
                    Exit Sub
                End If
                Dim sql As String = ""
                sql = "Select ItemNo,PoNum,PoNumItem,GoodsBarcode,GoodsCode,SupperItem,GoodsName,GoodsColor,GoodsSpec,Goodsamount,BatchNo,StorePlace,GoodsOther into #BB from V_GetCheckedBoNum where BoNum='" & Me.txtdiaobo.Text.Trim & "';"
                sql += "select * from #BB;"
                sql += "drop table #BB"

                DetailDS = ReturnDataset(sql)
                If DetailDS.Tables(0).Rows.Count <= 0 Then
                    MsgBox("該調撥單已入庫或不存在，不能重複操作！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Else
                    Me.DGV_Detail.DataSource = DetailDS.Tables(0)
                End If
            End If
        Catch ex As Exception
            MsgBox("txtdiaobo_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub txtBackNo_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtBackNo.KeyDown

        Try
            If e.KeyCode = Keys.Enter Then
                If Me.txtBackNo.Text.Length <= 0 Then
                    Exit Sub
                End If
                Dim sql As String = ""
                sql = "Select ItemNo,PoNum,PoNumItem,GoodsBarcode,GoodsCode,SupperItem,GoodsName,GoodsColor,GoodsSpec,Goodsamount,BatchNo,StorePlace,GoodsOther into #BB from V_GetCheckedBoNum where BoNum='" & Me.txtBackNo.Text.Trim & "';"
                sql += "select * from #BB;"
                sql += "drop table #BB"

                DetailDS = ReturnDataset(sql)
                If DetailDS.Tables(0).Rows.Count <= 0 Then
                    MsgBox("該返修出庫單不存在，不能入庫！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Else
                    Me.DGV_Detail.DataSource = DetailDS.Tables(0)
                End If

            End If
        Catch ex As Exception
            MsgBox("txtBackNo_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub txtSaleOrdeNo_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSaleOrdeNo.KeyDown

        Try
            If e.KeyCode = Keys.Enter Then
                If Me.txtSaleOrdeNo.Text.Length <= 0 Then
                    Exit Sub
                End If
                Dim sql As String = ""
                sql = "Select ItemNo,PoNum,PoNumItem,GoodsBarcode,GoodsCode,SupperItem,GoodsName,GoodsColor,GoodsSpec,Goodsamount,BatchNo,StorePlace,GoodsOther into #BB from V_SaleOrde_POS where PoNum='" & Me.txtSaleOrdeNo.Text.Trim & "';"
                sql += "select * from #BB;"
                sql += "drop table #BB"

                DetailDS = ReturnDataset(sql)
                If DetailDS.Tables(0).Rows.Count <= 0 Then
                    MsgBox("該銷售單不存在，不能入庫！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Else
                    For i As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                        DetailDS.Tables(0).Rows(i).Item("ItemNo") = Format(i + 1, "000")
                    Next
                    DetailDS.AcceptChanges()
                    Me.DGV_Detail.DataSource = DetailDS.Tables(0)
                End If
            End If
        Catch ex As Exception
            MsgBox("txtSaleOrdeNo_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DGV_Master_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DGV_Master.KeyDown

        Dim StoreHouse As String = ""
        Dim DeliverDate As String = ""

        Select Case e.KeyCode
            Case Keys.Up
                If Me.DGV_Master.CurrentRow.Index - 1 < 0 Then
                    Exit Select
                End If
                StoreHouse = Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells("ToStore").Value
                DeliverDate = Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells("DeliverDate").Value.ToString.Replace("-", "").Substring(0, 6)

                Select Case Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index - 1).Cells("BoStatus").Value
                    Case "保存"
                        MainForm.ToolStripPrint.Enabled = False
                        If StoreHouse = PubCompanyName Then
                            MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                            MainForm.ToolStripUnCheck.Enabled = False
                            MainForm.ToolStripComplete.Enabled = False
                            MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True
                            MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                        Else
                            MainForm.ToolStripCheck.Enabled = False
                            MainForm.ToolStripUnCheck.Enabled = False
                            MainForm.ToolStripComplete.Enabled = False
                            MainForm.ToolStripDelete.Enabled = False
                            MainForm.ToolStripEdit.Enabled = False
                        End If
                    Case "核准"
                        If StoreHouse = PubCompanyName Then
                            MainForm.ToolStripPrint.Enabled = True
                            MainForm.ToolStripCheck.Enabled = False
                            If DeliverDate < PeriodData Then
                                MainForm.ToolStripUnCheck.Enabled = False
                            Else
                                MainForm.ToolStripUnCheck.Enabled = True And UncheckEnable = True
                            End If
                            MainForm.ToolStripComplete.Enabled = True And CompleteEnable = True
                            MainForm.ToolStripDelete.Enabled = False
                            MainForm.ToolStripEdit.Enabled = False
                        Else
                            MainForm.ToolStripPrint.Enabled = False
                            MainForm.ToolStripCheck.Enabled = False
                            MainForm.ToolStripUnCheck.Enabled = False
                            MainForm.ToolStripComplete.Enabled = False
                            MainForm.ToolStripDelete.Enabled = False
                            MainForm.ToolStripEdit.Enabled = False
                        End If
                    Case "反核准"
                        MainForm.ToolStripPrint.Enabled = False
                        If StoreHouse = PubCompanyName Then
                            MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                            MainForm.ToolStripUnCheck.Enabled = False
                            MainForm.ToolStripComplete.Enabled = False
                            MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True And UncheckEnable = True
                            MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                        Else
                            MainForm.ToolStripCheck.Enabled = False
                            MainForm.ToolStripUnCheck.Enabled = False
                            MainForm.ToolStripComplete.Enabled = False
                            MainForm.ToolStripDelete.Enabled = False
                            MainForm.ToolStripEdit.Enabled = False
                        End If
                    Case "結案"
                        MainForm.ToolStripPrint.Enabled = True
                        MainForm.ToolStripCheck.Enabled = False
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                End Select
            Case Keys.Down
                If Me.DGV_Master.CurrentRow.Index + 1 >= Me.DGV_Master.RowCount Then
                    Exit Select
                End If
                StoreHouse = Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells("ToStore").Value
                DeliverDate = Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells("DeliverDate").Value.ToString.Replace("-", "").Substring(0, 6)

                Select Case Me.DGV_Master.Rows(Me.DGV_Master.CurrentRow.Index + 1).Cells("BoStatus").Value
                    Case "保存"
                        MainForm.ToolStripPrint.Enabled = False
                        If StoreHouse = PubCompanyName Then
                            MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                            MainForm.ToolStripUnCheck.Enabled = False
                            MainForm.ToolStripComplete.Enabled = False
                            MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True
                            MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                        Else
                            MainForm.ToolStripCheck.Enabled = False
                            MainForm.ToolStripUnCheck.Enabled = False
                            MainForm.ToolStripComplete.Enabled = False
                            MainForm.ToolStripDelete.Enabled = False
                            MainForm.ToolStripEdit.Enabled = False
                        End If
                    Case "核准"
                        If StoreHouse = PubCompanyName Then
                            MainForm.ToolStripPrint.Enabled = True
                            MainForm.ToolStripCheck.Enabled = False
                            If DeliverDate < PeriodData Then
                                MainForm.ToolStripUnCheck.Enabled = False
                            Else
                                MainForm.ToolStripUnCheck.Enabled = True And UncheckEnable = True
                            End If
                            MainForm.ToolStripComplete.Enabled = True And CompleteEnable = True
                            MainForm.ToolStripDelete.Enabled = False
                            MainForm.ToolStripEdit.Enabled = False
                        Else
                            MainForm.ToolStripPrint.Enabled = False
                            MainForm.ToolStripCheck.Enabled = False
                            MainForm.ToolStripUnCheck.Enabled = False
                            MainForm.ToolStripComplete.Enabled = False
                            MainForm.ToolStripDelete.Enabled = False
                            MainForm.ToolStripEdit.Enabled = False
                        End If
                    Case "反核准"
                        MainForm.ToolStripPrint.Enabled = False
                        If StoreHouse = PubCompanyName Then
                            MainForm.ToolStripCheck.Enabled = True And CheckEnable = True
                            MainForm.ToolStripUnCheck.Enabled = False
                            MainForm.ToolStripComplete.Enabled = False
                            MainForm.ToolStripDelete.Enabled = True And DeleteEnable = True And UncheckEnable = True
                            MainForm.ToolStripEdit.Enabled = True And EditEnable = True
                        Else
                            MainForm.ToolStripCheck.Enabled = False
                            MainForm.ToolStripUnCheck.Enabled = False
                            MainForm.ToolStripComplete.Enabled = False
                            MainForm.ToolStripDelete.Enabled = False
                            MainForm.ToolStripEdit.Enabled = False
                        End If
                    Case "結案"
                        MainForm.ToolStripPrint.Enabled = True
                        MainForm.ToolStripCheck.Enabled = False
                        MainForm.ToolStripUnCheck.Enabled = False
                        MainForm.ToolStripComplete.Enabled = False
                        MainForm.ToolStripDelete.Enabled = False
                        MainForm.ToolStripEdit.Enabled = False
                End Select
            Case Keys.Delete
                ActionDelete()
        End Select
    End Sub

    Private Sub txtGoodsamount_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        Try

            If e.KeyCode = Keys.Enter Then
                Dim Rows() As DataRow = GoodsDS.Tables(0).Select("BarCode='")
                Dim NewRow As DataRow = DetailDS.Tables(0).NewRow
                If Rows.Length > 0 Then
                    NewRow("ID") = DetailDS.Tables(0).Rows.Count + 1
                    NewRow("GoodsBarCode") = Rows(0).Item("BarCode") & ""
                    NewRow("GoodsCode") = Rows(0).Item("Code") & ""
                    NewRow("SupperItem") = Rows(0).Item("SupperItem") & ""
                    NewRow("GoodsName") = Rows(0).Item("Cnname") & ""
                    NewRow("GoodsColor") = Rows(0).Item("Color") & ""
                    NewRow("GoodsSpec") = Rows(0).Item("Spec") & ""
                    'NewRow("Goodsamount") = Me.txtGoodsamount.Text
                    'NewRow("BatchNo") = Me.txtBatch1.Text
                    'NewRow("storeplace") = Me.txtStorePlace1.Text
                    DetailDS.Tables(0).Rows.Add(NewRow)
                    DetailDS.AcceptChanges()
                    Me.DGV_Detail.DataSource = DetailDS.Tables(0)
                End If
            End If
        Catch ex As Exception
            MsgBox("txtGoodsamount_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub cbTradeCode_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cbTradeCode.KeyDown, cbInStoreType.KeyDown, cbFromStore.KeyDown, cbToStore.KeyDown, txtCarNo.KeyDown, txtDeliverNo.KeyDown, txtDeliverPerson.KeyDown, DateTimePicker1.KeyDown, txtRemark.KeyDown
        Try

            If e.KeyCode = Keys.Shift Then
                Select Case e.KeyCode
                    Case Keys.Enter
                        SendKeys.Send("+{TAB}")
                        SendKeys.Send("{F4}")
                End Select
            Else
                Select Case e.KeyCode
                    Case Keys.Enter
                        If sender.name = "txtRemark" Then

                        Else
                            SendKeys.Send("{TAB}")
                            SendKeys.Send("{F4}")
                        End If
                End Select
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub cbToStore_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbToStore.SelectedIndexChanged

        Try
            If Me.TabControl1.SelectedIndex = 1 Then
                Dim ToStore As String = Me.cbToStore.SelectedValue.ToString
                Dim Rows() As DataRow = StoreDS.Tables(3).Select("fCode='" & ToStore & "'")
                If Rows.Length > 0 Then
                    IsPlace = Rows(0).Item("fStorePlace") & ""
                End If
                If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                    Me.DGV_Detail.Columns("StorePlace").ReadOnly = Not IsPlace
                End If
                Dim sql As String = ""
                Dim m_DS As New DataSet
                sql = "select ID,fStorageId from BSC_Storage where fCode='" & Me.cbToStore.SelectedValue & "'"
                m_DS = ReturnDataset(sql)
            End If

        Catch ex As Exception
            MsgBox("cbToStore_SelectedIndexChanged:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub TreeView1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TreeView1.MouseClick
        Try

            If Me.TreeView1.SelectedNode.Tag <> PubCompanyCode Then
                Me.DGV_Detail.CurrentRow.Cells(13).Value = Me.TreeView1.SelectedNode.Text
                Me.Panel2.Visible = False
                Me.DGV_Detail.Focus()
                Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("StorePlace")
            End If
        Catch ex As Exception
            MsgBox("TreeView1_AfterSelect:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub TreeView1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TreeView1.KeyDown

        Try
            If e.KeyCode = Keys.Enter Then
                If Me.TreeView1.SelectedNode.Tag <> PubCompanyCode Then
                    Me.DGV_Detail.CurrentRow.Cells(13).Value = Me.TreeView1.SelectedNode.Text
                    Me.Panel2.Visible = False
                    Me.DGV_Detail.Focus()
                    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.CurrentRow.Index).Cells("StorePlace")
                End If
            End If
        Catch ex As Exception
            MsgBox("TreeView1_KeyDown:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub TreeView1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TreeView1.LostFocus
        Me.Panel2.Visible = False
    End Sub

    Private Sub DeleteToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Try
            If MessageBox.Show("您確定要刪除此元件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = DialogResult.Yes Then
                Dim element As String = ""
                Dim strsql As String = ""
                'If Me.lsvElement.SelectedItems.Count > 0 Then
                '    For i As Integer = 0 To Me.lsvElement.SelectedItems.Count - 1
                '        'element = Me.lsvElement.Items(i).SubItems(0).Text
                '        element = Me.lsvElement.SelectedItems(i).SubItems(0).Text
                '        strsql += "delete stor_element  where  element='" & element & "'" & vbCrLf

                '        'Me.lsvElement.Items.RemoveAt(Me.lsvElement.SelectedItems(i).Index)
                '    Next
                '    ReturnObject(strsql)

                '    For Each elementitem As ListViewItem In Me.lsvElement.SelectedItems
                '        elementitem.Remove()
                '    Next
                'End If
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub DGV_Sum_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGV_Sum.RowPostPaint
        e.Graphics.DrawString("合計:", Me.DGV_Sum.DefaultCellStyle.Font, Brushes.Black, e.RowBounds.Location.X + 8, e.RowBounds.Location.Y + 8)
    End Sub

    Private Sub txtGoodsBarCode_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtGoodsBarCode.KeyDown

        Me.txtGoodsBarCode.Focus()

    End Sub

    Private Sub txtGoodsBarCode_TextChanged1(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtGoodsBarCode.TextChanged

        Try
            If Me.txtGoodsBarCode.Text.Length > 0 Then


                Dim mRows() As DataRow = GoodsDS.Tables(0).Select("BarCode='" & Me.txtGoodsBarCode.Text & "'")
                Dim nRows() As DataRow = Nothing

                If mRows.Length > 0 Then
                    Dim NewRow As DataRow = DetailDS.Tables(0).NewRow

                    If Not DetailDS Is Nothing Then
                        nRows = DetailDS.Tables(0).Select("GoodsBarCode='" & Me.txtGoodsBarCode.Text & "'")
                        If nRows.Length > 0 Then
                            Me.txtGoodsBarCode.Text = ""
                            Me.txtGoodsBarCode.Focus()
                            Exit Sub
                        End If
                    End If

                    NewRow("ItemNo") = Format(DetailDS.Tables(0).Rows.Count + 1, "000")
                    NewRow("GoodsBarCode") = mRows(0).Item("BarCode") & ""
                    NewRow("GoodsCode") = mRows(0).Item("Code") & ""
                    NewRow("SupperItem") = mRows(0).Item("SupperItem") & ""
                    NewRow("GoodsName") = mRows(0).Item("Cnname") & ""
                    NewRow("GoodsColor") = mRows(0).Item("Color") & ""
                    NewRow("GoodsSpec") = mRows(0).Item("Spec") & ""
                    DetailDS.Tables(0).Rows.Add(NewRow)

                    DetailDS.AcceptChanges()
                    Me.DGV_Detail.DataSource = DetailDS.Tables(0)
                    Me.DGV_Detail.CurrentCell = Me.DGV_Detail.Rows(Me.DGV_Detail.Rows.Count - 2).Cells("Goodsamount")
                    Me.txtGoodsBarCode.Text = ""
                    Me.txtGoodsBarCode.Focus()
                End If
            End If

        Catch ex As Exception
            MsgBox("txtGoodsBarCode_TextChanged1:" & ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub txtelementnum_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtelementnum.KeyDown

        Try
            If Me.rb3.Checked = True Then
                If e.KeyCode = Keys.Enter Then
                    CreateElement()
                    Me.txtelementnum.Text = ""
                End If
            End If
        Catch ex As Exception
            MsgBox("txtelementnum_KeyDown:" & ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub dgv_Element_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles dgv_Element.RowPostPaint
        Try
            e.Graphics.DrawString(e.RowIndex + 1, dgv_Element.DefaultCellStyle.Font, Brushes.Black, e.RowBounds.Location.X + 5, e.RowBounds.Location.Y + 4)
        Catch ex As Exception
            MsgBox("dgv_Element_RowPostPaint:", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub
#End Region


    Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint

    End Sub

    Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        If Me.dgv_Element.Rows.Count = 0 Then
            MessageBox.Show("沒有數據可以保存", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2)
            Exit Sub
        End If
        Dim sql As String = ""
        Dim sqlConn As New SqlConnection
        Dim sqlcmd As New SqlCommand
        Dim DataTable As New DataTable
        Dim SqlBulk As SqlClient.SqlBulkCopy
        Dim mtable As DataTable = CType(Me.dgv_Element.DataSource, DataTable)

        sqlConn = GetConn()

        If sqlConn.State = ConnectionState.Closed Then
            sqlConn.Open()
        End If

        ''Dim transqlserver As SqlClient.SqlTransaction = sqlConn.BeginTransaction

        Dim transqlserver As SqlClient.SqlTransaction = sqlConn.BeginTransaction
        If IsElementSaved() = True Then
            Me.LabInfo1.Text = "元件已經存在！請重複生存"
            Me.LabInfo1.Visible = True
            ''mtable.Clear()
            Me.dgv_Element.DataSource = mtable
            Exit Sub
        End If

        If IsAdd = True Then
            Try
                If Convert.ToInt64(LastElement) > 0 Then
                    sql = "update Number  set  number=" & Val(LastElement) & ",UpdatePerson='" & PubUserName & "',UpdateComputer='" & My.Computer.Name & "',UpdateDate='" & Now.Date & "' where  billtype= 'ElementNum'"
                    With sqlcmd
                        .Connection = sqlConn
                        .Transaction = transqlserver
                        .CommandType = CommandType.Text
                        .CommandText = sql
                        .ExecuteNonQuery()
                    End With
                End If

                '數據批量插入到Stor_Element
                Dim dtTable As DataTable = ReturnTable(Me.txtBoNum.Text, 1)
                SqlBulk = New SqlClient.SqlBulkCopy(sqlConn, SqlClient.SqlBulkCopyOptions.Default, transqlserver)
                SqlBulk.DestinationTableName = "Stor_element"
                SqlBulk.BulkCopyTimeout = 100
                SqlBulk.WriteToServer(dtTable)

                '數據批量插入到Stor_Elmentstatus
                Dim dtSTable As DataTable = ReturnTable(Me.txtBoNum.Text, 2)
                SqlBulk = New SqlClient.SqlBulkCopy(sqlConn, SqlClient.SqlBulkCopyOptions.Default, transqlserver)
                SqlBulk.DestinationTableName = "Stor_Elmentstatus"
                SqlBulk.BulkCopyTimeout = 100
                SqlBulk.WriteToServer(dtSTable)


                IsAdd = False
                If Me.txtBoNum.Text.ToString.Length > 0 Then
                    MessageBox.Show("保存成功！", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information)
                End If
                ' mtable.Clear()
                Me.LabInfo1.Text = ""
                Me.dgv_Element.DataSource = mtable
                LastElement = 0
                transqlserver.Commit()
                sqlConn.Close()
            Catch ex As Exception
                transqlserver.Rollback()
                MsgBox("對不起，新增出錯。" & ex.Message, MsgBoxStyle.Information)
            End Try
        End If
    End Sub

    Public Function IsElementSaved() As Boolean
        Try
            Dim B As Boolean = False
            Dim sql As String = String.Empty
            Dim Element As System.Text.StringBuilder = New System.Text.StringBuilder
            Dim mTable As DataTable = CType(Me.dgv_Element.DataSource, DataTable)
            If mTable.Rows.Count > 0 Then
                For Each row As DataRow In mTable.Rows
                    If Element.ToString.Trim <> "" Then
                        Element.Append(",")
                    End If
                    Element.Append("'")
                    Element.Append(row("element"))
                    Element.Append("'")
                Next
                sql = "select * from (select element from  stor_element  union select element from stor_elementout ) a where element in (" + Element.ToString + ")"
                Dim rst As DataSet
                rst = Exec(sql, E_ExecType.DataSet)
                If rst.Tables(0).Rows.Count > 0 Then
                    B = True
                Else
                    B = False
                End If
            End If
            Return B
        Catch ex As Exception
            MessageBox.Show("Error:IsElementSaved" + ex.ToString)
        End Try
    End Function

    Private Sub BtnCasioXml_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCasioXml.Click
        Try
            Dim mBill As System.Text.StringBuilder = New System.Text.StringBuilder
            Dim SQL As String = String.Empty
            Dim mTable As DataTable = New DataTable
            Dim Xmlpath As String = ReturnXMLPathDown()
            Dim CasioNum As String = String.Empty

            If Me.DGV_Master.Rows.Count = 0 Then
                MessageBox.Show("請選擇要導出的入庫單號", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If
            If Me.DGV_Master.SelectedRows.Count = 0 Then
                Exit Sub
            Else
                For i As Integer = 0 To Me.DGV_Master.SelectedRows.Count - 1
                    If mBill.ToString.Length > 0 Then
                        mBill.Append(",")
                    End If
                    mBill.Append("'")
                    mBill.Append(Me.DGV_Master.SelectedRows(i).Cells("BoNum").Value)
                    mBill.Append("'")
                Next
            End If
            ''單號的數組
            Dim nums() As String = mBill.ToString().Replace("'", "").Split(",")
            '''''
            '在這里應該處理，只選中某些沒有被下載的數據
            '從日志里讀取是不是有，將所有的都添加到DataGrid中，只選中沒有其他Casio下載的
            ''''

            '此處是所有下載的記錄
            SQL = "select a.bonum as BillNo ,c.enname as itemNo,b.goodsamount as qty from Stor_TradeMaster "
            SQL &= " a left join Stor_TradeDetail b on a.bonum =b.bonum left join BSC_Goods c on b.goodsbarcode = c.barcode where 1=1 "
            SQL = SQL & " and a.bonum in (" & mBill.ToString & ")"
            mTable = ReturnDataset(SQL).Tables(0).Copy


            Dim Frm_SelectCasioNo As Frm_SelectCasioNo = New Frm_SelectCasioNo
            Frm_SelectCasioNo.ShowDialog()
            If Frm_SelectCasioNo.BtnYes.DialogResult <> DialogResult.OK Then
                Exit Sub
            End If
            CasioNum = Frm_SelectCasioNo.CBCasioNO.Text
            If Xmlpath.Length = 0 Then
                MessageBox.Show("沒有設置下載路徑", "路徑設置", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Exit Sub
            End If
            If CasioNum.Length = 0 Then
                MessageBox.Show("請選擇Casio編號", " 提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If

            '此處是已經被下載過的記錄
            Dim sqlstr As String = "select Convert(bit,0) as Checked,CasioID,LogType,LogContent, "
            sqlstr += "OperateType,OperateTime from CasioLog where LogContent in (" & mBill.ToString & ")"
            sqlstr += "and ModelName='" + Me.GetType.Name + "' and LogType in('下載記錄')"
            Dim casioLog As DataTable = Exec(sqlstr, E_ExecType.DataTable)

            '選擇界面（已經下載過的記錄是否還重新下載）
            Dim frmCasioOp As Frm_CasioSelectItems
            '沒有選中的項目（曾經下載過，現在不再下載的選項）
            Dim unselectTable As DataTable
            Dim selectTable As DataTable
            If casioLog.Rows.Count > 0 Then
                Dim infoText = "下列入庫單已被下載；" + Microsoft.VisualBasic.vbCr + "如需重復下載（慎重），請選擇"
                frmCasioOp = New Frm_CasioSelectItems(infoText, "重復下載對話框")
                frmCasioOp.InTable = casioLog
                'frmCasioOp.ShowDialog()
                If Not frmCasioOp.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    Return
                End If
                unselectTable = frmCasioOp.OutTableUnSelected
                selectTable = frmCasioOp.OutTableSelected
            Else
                unselectTable = New DataTable
                selectTable = New DataTable
            End If
            Dim bonumcount As Int32 = 0

            Xmlpath = Xmlpath + "InStor-" + Frm_SelectCasioNo.CBCasioNO.Text.ToString.Trim + ".XML"

            Dim ExportTable As DataTable = mTable.Clone()
            '導出的單號是這樣的：
            '1.如果不是重復的則添加
            '2.如果是重復的：
            '   (1)有選中則添加
            '   (2)沒有任何選中則不應下載
            For Each row As DataRow In mTable.Rows
                If (casioLog.Select("LogContent='" + row("BillNo").ToString().Replace("'", "") + "'").Length = 0) Then
                    ExportTable.ImportRow(row)
                ElseIf selectTable.Select("Item='" + row("BillNo").ToString().Replace("'", "") + "'").Length > 0 Then
                    ExportTable.ImportRow(row)
                End If
            Next
            ExportTable.AcceptChanges()
            ExportTable.WriteXml(Xmlpath, System.Data.XmlWriteMode.WriteSchema, True)
            'mTable.WriteXml(Xmlpath, System.Data.XmlWriteMode.WriteSchema, True)

            '寫入日志
            Dim sqlinFormart As String = "insert into CasioLog values('" & Me.GetType().Name & "','" & CasioNum & "','入庫單',GetDate(),'下載記錄','{0}')"


            For Each num As String In nums
                '導出的單號是這樣的：
                '1.如果不是重復的則添加
                '2.如果是重復的：
                '   (1)有選中則添加
                '   (2)沒有任何選中則不應下載
                If casioLog.Select("LogContent='" + num + "'").Length = 0 Then
                    bonumcount = bonumcount + 1
                    Dim sqlin As String = String.Format(sqlinFormart, num)
                    Exec(sqlin, E_ExecType.ExecuteNonQuery)
                ElseIf selectTable.Select("Item='" + num + "'").Length > 0 Then
                    bonumcount = bonumcount + 1
                    Dim sqlin As String = String.Format(sqlinFormart, num)
                    Exec(sqlin, E_ExecType.ExecuteNonQuery)
                End If
            Next

            If bonumcount > 0 Then
                MessageBox.Show("" + bonumcount.ToString() + "條入庫單保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                MessageBox.Show("沒有保存任何記錄", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show("Error:BtnCasioXml_Click" + ex.ToString)
        End Try
    End Sub

    Private Sub DGV_Master_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles DGV_Master.Paint
        FormatDgrd(DGV_Master, "BoStatus")
    End Sub

    Private Sub GroupBox4_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GroupBox4.Enter

    End Sub

    Private Sub InputMauToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InputMauToolStripMenuItem.Click

        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then


            If Me.cbInStoreType.SelectedIndex <> 7 Then
                MessageBox.Show("請選擇半成品入庫", "加朗軟體", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.cbInStoreType.Focus()
                Me.cbInStoreType.SelectedIndex = 7
                Exit Sub
            End If

            Dim sql As String = String.Empty
            Dim SelectMau As New Frm_SelectMau
            Dim DT As DataTable

            If SelectMau.ShowDialog() = DialogResult.OK Then
                If SelectMau.DataGridView1.Rows.Count > 0 Then
                    DT = CType(SelectMau.DataGridView1.DataSource, DataTable)
                Else
                    Exit Sub
                End If
            Else
                Exit Sub
            End If

            Dim DATable As New DataTable

            '篩選出選擇的記錄
            Dim ISSELECTEDRows() As DataRow = DT.Select("ISSELECTED= TRUE")
            For i As Int32 = 0 To ISSELECTEDRows.Length - 1
                Dim GoodBarCode As String = ISSELECTEDRows(i)("Barcode").ToString()
                Dim QTY As Int32 = CType(ISSELECTEDRows(i)("qty").ToString(), Int32)
                AddDataToGrid(GoodBarCode, QTY)
            Next

        End If

    End Sub

    Private Sub DGV_Detail_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Detail.CellContentClick

    End Sub
End Class

